在我的应用程序中,为了调用所有的POST请求,我使用了一个service。
当我从服务器获得特定于的代码(E.x : 401)时,我调用一个API来获取新的令牌。
在收到另一个令牌之前,如果有任何其他API调用,我会将所有这些请求存储在一个数组中。可能是n请求。现在假设在调用newToken API的过程中有3个API调用。
一旦我得到一个新的令牌,我必须在所有后续API中传递它,现在我必须执行所有挂起的API请求,并将数据提供给它们各自的调用。
代码示例:
api.service.ts
POST(URL , param){
return new Observable<any>(observer => {
let headers = new HttpHeaders({
'Content-Type': 'Content-Type': 'application/json'
});
let options = {
headers: headers
};
this.http.post(URL, param, options)
.subscribe(data => {
var apiRes: any = data;
this.inValidSession();
observer.next();
observer.complete();
}
......
// For execute pending request I have set this
for (let i = 0; i < this.queue.length; i++) {
this.REPOST(this.queue[i].param, this.queue[i].url).subscribe((queueResponse) => {
observer.next(queueResponse);
observer.complete();
this.queue.shift();
});
}
}user.component.ts
ngOnInit(){
this.getUserData();
this.getProductData();
}
getUserData(){
this.apiService.post({},'/apiName').subscribe((response) => {
console.log(response);
})
}
getProductData(){
this.apiService.post({},'/apiName2').subscribe((response) => {
console.log(response);
})
}问题是,当我执行所有挂起的API时,我会在控制台中获得数据。而不是subscribe从服务文件到相应的.ts文件的函数。
注意:我只在一个函数中获得订阅数据,而不是每个函数。换句话说,我在getProductData()函数中得到了这两个API res。我也不知道原因。
如果有人有解决办法,请帮助我。
发布于 2018-10-26 06:25:07
您可以使用
forkJoin()要同时处理多个调用,您可以调用多个request,在订阅之后您将得到一个resoponse的array。
例如
forkJoin(Service1.call1,
Service2.call2)
.subscribe(([call1Response, call2Response]) => {其中service1和service2是具有ccall1和call2功能的服务,具有return类型的Observable。
你可以找到更多的这里
发布于 2019-11-22 06:38:52
Easy方法
使用forkjoin()
public sample(): Observable<any[]>
{
let call1=this.http.get(this._url+'/v1/sample1')
let call2=this.http.get(this._url+'/v1/sample2')
let call3=this.http.get(this._url+'/v1/sample3')
return forkJoin([call1, call2,call3]);
}发布于 2019-08-29 08:42:26
使用来自zip的rxjs库
import { zip } from "rxjs";
myFun() {
zip(service.api1, service.api2)
.subscribe(([response1, response2]) => {
console.log(response1);
console.log(response2);
})
}https://stackoverflow.com/questions/53002461
复制相似问题