【发布时间】:2019-01-09 15:12:27
【问题描述】:
我正在尝试将现有的 AngularJs 代码迁移到 Angular 5。我目前在 forEach 函数中运行许多 API 调用。以前我曾经在每个函数中运行 $q.defer ,并在成功或错误函数调用中运行 .resolve() 。在那之后$q.all。现在我不确定如何将它与 observables 一起使用。
这就是我的组件的外观。
testArray = [1,2,3,4,5,.6];
resultArray = [];
constructor(private timeoutService: TimeoutService) {
this.testFn();
}
testFn(){
this.testArray.forEach((n) => {
this.timeoutService.getItemsCallback(n, this.successFn.bind(this), this.errorFn.bind(this))
})
}
successFn(r){
this.resultArray.push(r);
console.log(r)
}
errorFn(e){
this.resultArray.push(e);
console.log(e);
}
这是我的服务文件。
public GetItems(request: any): Observable<any> {
console.log(request)
return this.http.get(`https://jsonplaceholder.typicode.com/posts/${request}`);
}
getItemsCallback(request, successFn, errorFn) {
this.GetItems(request).
subscribe(
response => {
successFn(response);
},
error => {
errorFn();
}
);
}
我想在所有 API 调用完成后做点什么。我看到有一个名为 forkJoin 的函数,但我不知道如何使用它。 这是一个stackblitz链接。 https://stackblitz.com/edit/angular-suetah?file=src%2Fapp%2Ftimeout.service.ts
【问题讨论】:
-
将
forkJoin或zip用于$q.all。
标签: angular rxjs observable