khu*_*boo 2 request observable angular
在我的应用程序中,要调用POST我使用的所有请求service。
当我从服务器获取特定代码(例如:401)时,我调用 API 来获取新令牌。
直到收到另一个令牌,如果有任何其他 API 调用,我将所有这些请求存储在一个数组中。它可能是n 个请求。现在假设有 3 个 API 调用,同时对 newToken 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();
});
}
}
Run Code Online (Sandbox Code Playgroud)
用户组件.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);
})
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我执行所有挂起的 API 时,我会在控制台中获取数据。但不是subscribe从服务文件到相应.ts文件的功能。
注意:我只在一个函数中获取订阅数据,而不是每个函数。换句话说,我得到了两个 API res 的getProductData()功能。我不知道为什么。
如果有人有解决方案,请帮助我。
您可以使用
forkJoin()
Run Code Online (Sandbox Code Playgroud)
同时处理多个呼叫,您可以同时呼叫多个request,订阅后您将得到array回复。
例如
forkJoin(Service1.call1,
Service2.call2)
.subscribe(([call1Response, call2Response]) => {
Run Code Online (Sandbox Code Playgroud)
其中 service1 和 service2 是具有函数 ccall1 和 call2 的服务,它们具有return类型 Observable
你可以在这里找到更多
| 归档时间: |
|
| 查看次数: |
26448 次 |
| 最近记录: |