你能告诉我为什么这个()
成功方法没有解雇吗?当我使用forkjoin()
时,它运行良好。每次都没有激活成功方法吗?希望它就像final
块上的try-catch
方法。
注意:请参阅内嵌评论。
.TS
getAllBooksReadAndUnRead(id: number, loader?) {
this.article.getAllBooksReadAndUnRead(id)
.map((res: any) => res.json())
.subscribe(res => {
this.setAllData(res); //it comes to here
this.loadingControllerService.dismissLoader(loader);//I have to put this here.Then no problem.But I think it is duplicate of work???
},
error => {this.loadingControllerService.dismissLoader(loader);},
() => {this.loadingControllerService.dismissLoader(loader);}//not fire
});
}
Api通话
getAllBooksReadAndUnRead(bookId) {
return this.apiSer.get(`${config.fromThisBook}?page=all&book[]=${bookId}`);
}
通用方法:
get(api) {
return new Observable(observer => {
let header = new Headers();
this.createHeader(header)
.then(() => {
let options = new BaseRequestOptions();
options.withCredentials = true;
options.headers = header;
this.http.get(api, options)
.subscribe(response => {
observer.next(response);
}, (e) => {
observer.error(e);
});
})
})
}
发表()
post(url, params): Observable<any> {
return new Observable(observer => {
let header = new Headers();
this.createHeader(header)
.then(() => {
let options = new RequestOptions({ headers: header });
this.http.post(url, params, options)
.subscribe(response => {
observer.next(response);
observer.complete();
}, (e) => {
observer.error(e);
});
})
})
}
答案 0 :(得分:3)
问题是您永远不会在自定义生产者中触发完成。你需要这样的东西:
get(api) {
return new Observable(observer => {
let header = new Headers();
this.createHeader(header)
.then(() => {
let options = new BaseRequestOptions();
options.withCredentials = true;
options.headers = header;
this.http.get(api, options).subscribe(
response => observer.next(response),
(e) => observer.error(e),
() => observer.complete(); <-------------------------
);
})
})
}
此外,我认为您不需要自定义制作人,请尝试这样:
get(api) {
return Observable.from(this.createHeader()).map((header) => {
let options = new BaseRequestOptions();
options.withCredentials = true;
options.headers = header;
return this.http.get(api, options);
}).mergeAll();
}
以下是它的工作原理:
Observable.from(this.createHeader())
返回一个可以在承诺解决后传递值的observable .map((header) => {
观察返回的promise所带来的值并发出HTTP请求并以observable的形式返回结果mergeAll()
- 由于上一个操作返回并且可观察,我们需要将其展平答案 1 :(得分:0)
我尽量避免将代码块包装在括号中,除非我必须这样做,因为这样会更容易混淆它们的位置。例如,您在倒数第二行中有一个可能导致问题的额外结束}:
getAllBooksReadAndUnRead(id: number, loader?) {
this.article.getAllBooksReadAndUnRead(id)
.map((res: any) => res.json())
.subscribe(res => {
this.setAllData(res);//it comes to here
},
error => {this.loadingControllerService.dismissLoader(loader);},
() => {this.loadingControllerService.dismissLoader(loader);}//not fire
);
}
我倾向于简化这样的括号:
getAllBooksReadAndUnRead(id: number, loader?) {
this.article.getAllBooksReadAndUnRead(id)
.map(res: any => res.json())
.subscribe(res => {
this.setAllData(res);//it comes to here
},
error => this.loadingControllerService.dismissLoader(loader),
() => this.loadingControllerService.dismissLoader(loader)//not fire
)};