如何触发需要后端数据的功能?我的目标是使用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
个对象为空,应用程序崩溃。加载getPersons()
和getCities()
时如何触发getCars()
?
已经尝试AfterViewInit
使用setTimeout
解决方法无效。
答案 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();
});
});
}
我希望这对你也有帮助。