【问题标题】:Angular 4 fire function after server data loaded加载服务器数据后的Angular 4触发功能
【发布时间】:2018-04-27 09:05:38
【问题描述】:

如何触发需要后端数据的函数?我的目标是使用 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 对象为空并且应用程序崩溃。加载getCities()getCars() 时如何触发getPersons()? 已经尝试了 AfterViewInitsetTimeout 的解决方法,但这些方法不起作用。

【问题讨论】:

  • 它们有什么关系?它们是异步的吗?
  • 请出示getCars()getCities()getPersons()的代码。
  • 更新添加的服务和组件

标签: javascript angular typescript promise fetch


【解决方案1】:

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

 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();
        });
      });
  }

希望对你也有帮助。

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多