如何调用多个API并在angular 6中进行订阅? [英] How to call multiple API and subscribe in angular 6?
问题描述
在我的应用程序中,我使用service
来调用所有POST
请求.
In my app, to call all the POST
request I have used a service
.
当我从服务器获取特定代码(E.x:401)时,我将调用API来获取新令牌.
When I get a specific code (E.x : 401) from the server, I call an API to fetch new token.
直到收到另一个令牌,如果还有其他API调用,我会将所有这些请求存储在一个数组中.可能是 n 个请求.现在,假设正在进行3个API调用,而对newToken API的调用正在进行中.
Till the another token is received, if there's any other API call from, I store all those requests in an array. It may be n requests. For now assume there are 3 API call while the call for newToken API is in progress.
一旦获得新令牌,我必须在所有后续API中传递该令牌.现在,我必须执行所有待处理的API请求,并将数据提供给它们各自的调用.
Once I get a new token I have to pass that in all the subsequent API's. Now I have to execute all the pending API requests and give data to their respective calls.
代码示例:
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
文件的功能.
Issue is , when I execute all pending API's, I get data in the console. But not subscribe
from service file to respective .ts
file's function.
注意:我仅在一个函数中获得订阅数据,而不是每个函数.换句话说,我在getProductData()
函数中都获得了两个API资源.我不知道为什么.
Note: I get subscribed data in only one function not each. In other words, I get both API res in getProductData()
function. I don't know why.
如果有任何解决方案,请帮助我.
Please help me if any one has solution.
推荐答案
您可以使用
forkJoin()
要同时处理多个呼叫,您可以在其中呼叫多个request
,订阅后,您将获得array
响应.
To handle multiple calls at the same time, where you can call multiple request
and after subscribing you will get an array
of resoponse.
例如
forkJoin(Service1.call1,
Service2.call2)
.subscribe(([call1Response, call2Response]) => {
其中service1和service2是具有功能ccall1和call2且具有return
类型Observable
Where service1 and service2 are service which have function ccall1 and call2 , that are having return
type Observable
您可以找到更多的此处
这篇关于如何调用多个API并在angular 6中进行订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!