简体   繁体   中英

Angular 4 fire function after server data loaded

How to fire function that requires back end data? My target is to fire getPersons() which depends on getCities() and getCars() with Angular 4.

export class Person {
  constructor(
    public cities: any[],
    public cars: any[]
  ) { }
}

In component I call:

  public ngOnInit(): void {
    this.getCars();
    this.getCities();
    this.getPersons();
  }

EDIT Service:

  public getCars(): Observable<CarsList> {
    return this.http.get(this.carsUrl)
      .map((res: Response) => res.json())
      .catch((error: Response) => Observable.throw(
        this.errorHandlerService.showError(getCarsError)));
  }

Component:

 public getPersons(): void {
    this.personsService.getPersons()
        .subscribe(
          (data) => {
            this.persons = data;
            this.persons .forEach((person, index) => {
              person.carName = this.cars.find((car) => car.id === person.carId).name;
              console.log('error here because this.cars is still undefined')
            }
        )
 }

Problem is that getPersons() is fired before getCities() and getCars() are loaded and data depends on it. So this.cities or this.cars objects are null and app crash. How to fire getPersons() when getCities() and getCars() are loaded? Already tried AfterViewInit with setTimeout workarounds which are not working.

Solved by this way: Service:

 public async getCars(): Promise<DetailedObjectsList> {
    try {
      const response = await this.http.get(this.carsUrl).toPromise();
      return response.json();
    } catch (e) {
      this.errorHandlerService.showError(carsError);
    }
  }

Component:

  public async getCars() {
    await this.carsService.getCars()
      .then((data) => {
        if (!isNullOrUndefined(data)) {
          this.cars = data.detailedObjects;
        }
      });
  }

and most important:

 public ngOnInit(): void {
     this.getCars()
      .then(() => {
        this.getCities()
          .then(() => {
            this.getPersons();
        });
      });
  }

I hope that helps for you too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM