使用Angular/RXJS逐个发送两个HTTP请求,其中第二个请求需要第一个请求?
目前,我的代码是通过相互嵌套观测值来实现的使用Angular/RXJS逐个发送两个HTTP请求,其中第二个请求需要第一个请求?,angular,rxjs,angular-http,Angular,Rxjs,Angular Http,目前,我的代码是通过相互嵌套观测值来实现的 makeRequest() { return this.http.get().map((response: Response) => { return this.http.get(response.doSomething()); } } 当我需要使用它时,我也使用嵌套订阅它们 我相当肯定这不是正确的方法,现在我需要一种方法来做一些事情,大致如下: ->发出请求->检查回复->如果回复指示令牌已过时->获取新令牌并再次执行请求->
makeRequest() {
return this.http.get().map((response: Response) => {
return this.http.get(response.doSomething());
}
}
当我需要使用它时,我也使用嵌套订阅它们
我相当肯定这不是正确的方法,现在我需要一种方法来做一些事情,大致如下:
->发出请求->检查回复->如果回复指示令牌已过时->获取新令牌并再次执行请求->否则将结果传递给
实现这一目标的推荐方法是什么
非常感谢,使用flatMap或switchMap并有条件地返回不同的可观察值
auth() {
return this.http.get().flatMap((response: Response) => {
if (token not expire....) {
// pass on the response
return Observable.of(response)
}
return this.http.get(response.getToken()).mapTo(Observable.throw('Retry'));
}).retry()
}
我们使用
mergeMap/flatMap
在可观察对象上迭代。mergeMap将从内部observable中提取observable并将其传递给父流
makeRequest() {
return this.http.get().pipe(
mergeMap(response: Response => this.http.get(response.doSomething())
);
}
我想你可以用
这里,根据第一个回调请求的结果,第一个回调请求将首先发生,然后是第二个回调请求,因此,如果第一个回调请求失败,第二个回调请求将不会发生,您可以像这样链接任意数量的依赖请求
或者您可以使用模式执行此操作我是否可以执行此操作,以便如果令牌过期,它将获取令牌,然后再次发送请求并返回响应?编辑答案。我故意抛出一个错误,以便再次重复整个链。
async.waterfall([
function(callback) {
this.http.get(url1).then(res1 => {
callback(null, res1);
}).catch(err => {
callback(err);
})
},
function(res1, callback) {
this.http.get(url2).then(res2 => {
callback(null, res2);
}).catch(err => {
callback(err);
})
},
], function (err, result) {
// result now equals res2
// err here is the first error occure
});