【发布时间】:2017-12-12 16:22:52
【问题描述】:
我正在努力让 http 调用等待上一个调用完成,然后再进行下一个调用。 getThings 调用我的 HTTP 服务,该服务最终也会发送一条 getMessage 订阅的消息。我这样做的原因是因为多个组件使用此服务和 getThings()。我想我需要使用承诺,但不确定如何实施。
我的组件
getThings(endpoint:any){
this.getThingsService.getThings(endpoint);
this.getThingsService.clearMessage();
this.subscription = this.getThingsService.getMessage()
.takeUntil(this.ngUnsubscribe)
.subscribe(message => {
if(message) {
this.data = message;
}
})
}
//I want to wait for getThings to finish before calling getOtherThings.
getOtherThings(data:any){
//make another http call
}
服务提供者
getThings(link:any){
interface ItemsResponse {
results: string[];
}
this.http
.get<ItemsResponse>(link, {
observe: 'response'
})
.retry(3)
.takeUntil(this.ngUnsubscribe)
.subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
break;
case HttpEventType.Response:
this.handleData(event.body);
}
},
(err: HttpErrorResponse) => {
//error
}
)
}
handleData(allAppDetails: any){
this.clearMessage();
this.sendMessage(allAppDetails);
}
sendMessage(message: {}) {
this.subject.next(message);
}
clearMessage() {
this.subject.next(null);
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
////////新解决方案////////
组件:
getThings(endpoint){
this.subscription = this.getThingsService.getThings(endpoint)
.flatMap(res => {
if(res){
console.log("get things complete, call getOtherThings")
}
return this.getThingsService.getOtherThings(endpoint)
})
//this doesnt seem to catch anything
.catch(err => {
throw err
})
.subscribe(
res => { // res is the result of the second http request
if(res){
console.log("other things response");
}
},
//would this catch errors for both http calls?
err => {
console.log(err)
});
}
服务
getThings(link:any) {
interface ItemsResponse {
results: string[];
}
return this.http
.get<ItemsResponse>(link, {
observe: 'response'
})
getOtherThings(link:any) {
interface ItemsResponse {
results: string[];
}
return this.http
.get<ItemsResponse>(link, {
observe: 'response'
})
如何使用这种方法捕获 http 错误?
【问题讨论】: