加载服务器数据后的Angular 4 fire功能

时间:2017-11-14 12:03:43

标签: javascript angular typescript promise fetch

如何触发需要后端数据的功能?我的目标是使用Angular 4触发getPersons()取决于getCities()getCars()

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

在组件中我打电话:

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

编辑 服务:

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

组件:

 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')
            }
        )
 }

问题是在加载getPersons()getCities()并且数据依赖于它之前触发了getCars()。因此this.citiesthis.cars个对象为空,应用程序崩溃。加载getPersons()getCities()时如何触发getCars()? 已经尝试AfterViewInit使用setTimeout解决方法无效。

1 个答案:

答案 0 :(得分:0)

通过这种方式解决: 服务:

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

组件:

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

最重要的是:

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

我希望这对你也有帮助。