How to access return of an Eventemitter object created from http.get

Asked

Viewed 95 times

0

I have a service that performs a get at a certain address.

@Injectable({
  providedIn: 'root'
})
export class PersonService {

  private person: Observable<Person>;
  personBroadcast = new EventEmitter();

  constructor(private http: HttpClient) { }

  getPersonByCode(code: number): Observable<Person> {
    this.person = this.http.get<Person>(environment.urlHumanResourceService + 'api/person/code/' + code);
    this.personBroadcast.emit(this.person);
    return this.person;
  }
}

I’m using it in the following component:

export class PatientComponent implements OnInit {

  private person: Person;

  constructor(private personService: PersonService) { }

  ngOnInit() {
  }

  onEnter(value: number) { this.getPersonByCode(value);  }

  public getPersonByCode(code: number) {
    this.personService.getPersonByCode(code).subscribe((data: Person) => {
      this.person = data;
    });
  }
}

Up to this point everything is working as expected, but I need to use some data of the result of this get in another component. Searching I found the solution to use an Eventemitter to communicate the get result.

export class AttendanceComponent implements OnInit {

  private attendance: Attendance;
  private person: Person;

  constructor(private personService: PersonService) { }

  ngOnInit() {
    this.personService.personBroadcast.subscribe((data: Person) => {
      this.person = data;
    });
  }

  newClinicalAppointment(observation: string) {
    console.log(this.person);
    this.attendance = new Attendance(
      null,
      null,
      this.person,
      new Date,
      AttendanceTypes.ClinicalAppointment,
      observation
    );
  }
}

Testing I’m getting an observable object and can’t subscribe access to the data I expected. I tested by passing an object created in hand in Emit() and in this case I was successful.

What was done wrong? The solution I’m using for this problem is the best approach?

  • Event emmiter and a child component for a parent to make this communication between services better use Behavior Subject

  • Take a look at my answer https://answall.com/questions/305588/sharedataintercomponents-angular-6/305989#305989

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.