In my app, to call all the POST request I have used a service.
When I get a specific code (E.x : 401) from the server, I call an API to fetch new token.
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.
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.
Code Example :
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);
})
}
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.
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.