【发布时间】: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.cities 或this.cars 对象为空并且应用程序崩溃。加载getCities() 和getCars() 时如何触发getPersons()?
已经尝试了 AfterViewInit 和 setTimeout 的解决方法,但这些方法不起作用。
【问题讨论】:
-
它们有什么关系?它们是异步的吗?
-
请出示
getCars()、getCities()和getPersons()的代码。 -
更新添加的服务和组件
标签: javascript angular typescript promise fetch