简体   繁体   English

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

[英]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. 我的目标是使用Angular 4 getCars()依赖于getCities()getCars() getPersons()

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. 问题在于,在getCities()getCars()以及数据依赖它之前会触发getPersons() So this.cities or this.cars objects are null and app crash. 因此this.citiesthis.cars对象为null,导致应用崩溃。 How to fire getPersons() when getCities() and getCars() are loaded? 加载getCities()getCars()时如何触发getPersons() Already tried AfterViewInit with setTimeout workarounds which are not working. 已经使用setTimeout解决方法尝试了AfterViewInit ,但该方法不起作用。

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. 希望对您也有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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