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

0

I have a service that performs a get on a given 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;
    });
  }
}

So far everything is working as expected, but I need to use some data from the result of that get on another component. Searching I found the solution to use an EventEmitter to communicate the result of the get.

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 I can not get the subscribe to access the data I was expecting. I tested it by passing an object created in the hand in emit () and in this case I succeeded.

What was done wrong? Is the solution I'm using for this problem the best approach?

    
asked by anonymous 27.08.2018 / 14:50

0 answers