Search code examples
angularasynchronouseventemitter

Angular EventEmitter after getting some data from back-end


I have next code:

streets: Street[] = [];
@Output() sendStreets =  new EventEmitter<Street[]>();

triggerLoading(trig: string){
    switch(trig) {
      case 'street': {
        this.loadStreets(this.district);

        //sending data
        this.sendStreets.emit(this.streets);

        this.street = this.building = this.apartment = undefined;
        this.buildings = this.apartments = this.subscribers = [];
        break;
      }
}

So the problem is that this.loadStreets(this.district); method requests from back-end array of streets and when I send data this.sendStreets.emit(this.streets); I get in the parent component empty array in the 1st request, and then in the 2nd one I get data which I should get in the 1st request etc. So, for example I SHOULD get:

1 request: "[Str1, St2, St2]", 2request: ["Str10, Str20, Str30"], 3request: [Str20, Str30, Str40] etc.

BUT I get: `

1request: "[]", 2 request: "[Str1, St2, St2]", 3request: ["Str10, Str20, Str30"] etc.

`

How can I emit it asynchronously, I mean after loadStreet will finish executing I'll emit data?

UPD: How I receive data:

<hs-filter> (sendStreets)= "getStreets($event)" </hs-filter >

getStreets(streets: Street[]){
    console.log(streets);
    this.streets = streets;
    this.buildings = this.apartments = [];

    this.streets.forEach(street => {
      this.addresses.push(
        new AddressItem(street.id, 'street', street.title));
    });
  }

Solution

  • class EventEmitter extends Subject { constructor(isAsync: boolean = false) - So for your case: @Output() sendStreets = new EventEmitter(true);