在我的应用程序中,调用所有POST
请求我已经使用了service
.
当我得到一个specific code (例如: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();
});
}
}
用户组件.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
文件的功能。
注意:我仅在一个函数中获取订阅数据,而不是在每个函数中获取订阅数据。换句话说,我得到了两个 API resgetProductData()
功能。我不知道为什么。
如果有人有解决方案,请帮助我。