![](/img/trans.png)
[英]How to handle/detect canceled requests in http interceptor Angular?
[英]How to hold off certain HTTP requests at HTTP Interceptor in Angular
我有一個Angular代碼,后面的故事就是這樣。 我有3個HTTP調用,而從一個調用中,我需要另外兩個HTTP調用所需的特殊標頭(X),但我無法控制這些調用的執行。 因此,當需要X標頭的HTTP調用出現在給我X標頭的HTTP調用之前時,我該如何推遲該調用並放開特定的HTTP調用並獲取X標頭,並繼續使用X標頭附加到其余的HTTP調用中? 似乎我正在嘗試創建HTTP調用隊列,直到獲得X標頭並再次繼續其余的調用為止。 一些幫助,將不勝感激。 代碼如下。
模板:
<button class="btn btn-primary" (click)="do()"> Do </button>
App.ts文件
export class AppComponent {
constructor(private dataService: DataService) {}
public do(): void {
this.dataService.first().subscribe();
this.dataService.second().subscribe((res) => {
this.dataService.third().subscribe();
});
}
}
具有3個HTTP調用的data-service.ts
const httpOptions1 = {
headers: new HttpHeaders({ 'A': 'A' })
};
const httpOptions2 = {
headers: new HttpHeaders({ 'X': 'X' })
};
const httpOptions3 = {
headers: new HttpHeaders({ 'B': 'B' })
};
@Injectable()
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
public first(): Observable<any> {
console.log('Call One')
return this.http.get(`${this.apiUrl}`, httpOptions1);
}
public second(): Observable<any> {
console.log('Call Two')
return this.http.get(`${this.apiUrl}`, httpOptions2);
}
public third(): Observable<any> {
console.log('Call Three')
return this.http.get(`${this.apiUrl}`, httpOptions3);
}
}
這是第二個具有X標頭的調用,我想從Interceptor中進行的操作是,當first()
調用關閉時,我想按住它,然后讓second()
調用繼續並獲取X標頭,然后從攔截器級別重新運行first()
調用。
以下是攔截器的代碼
private pocessed: boolean = false;
private queue: any[] = [];
constructor() {}
public intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<any> {
/**
* Filter a certain http call with a certain X http header where this call provides a new header
* to be appended to all other http calls
*/
if (req.headers.has('X')) {
return delegate.handle(req).do((event) => {
if (event.type === HttpEventType.Response) {
// new header data acquired; hence the boolean turned to true
this.pocessed = true;
}
});
} else if (this.pocessed) {
/**
* if new header data acquired, append the new header to the rest of the calls
*/
if (this.queue.length > 0) {
// append header data to previous http calls
this.queue.forEach(element => {
let request = new HttpRequest(element.req['method'], element.req['url'], element.req['body'], {
headers: element.req['headers'],
reportProgress: true,
params: element.req['params'],
responseType: element.req['responseType'],
withCredentials: element.req['withCredentials']
});
// this.fakeIntercept(request, element.next);
});
}
// if new header data acquired, append the header to the rest of the calls
req = req.clone({ setHeaders: { 'X': 'X' } });
return delegate.handle(req).do((event) => console.log(event));
} else {
/**
* these http calls need X header but the call to get the X header hasnt gone yet
* therefor storing these calls in a queue to be used later when the header arrives
*/
this.queue.push({req: req, next: delegate});
return Observable.empty<any>();
}
}
fakeIntercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<any> {
req = req.clone({ setHeaders: { 'X': 'X' } });
return delegate.handle(req);
}
如果你們需要任何澄清,請在評論中打我。 如果您發現我在這里做錯了什么,請與我分享。 歡迎對代碼進行任何改進。
我找到了一個解決方案,它對我的atm很好。 我正在使用SUbject流來模仿Queue的行為,並讓請求堆積起來,直到從X標頭http調用獲取數據為止。 下面是代碼。 希望有道理。 干杯!
public intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<any> {
return Observable.create(observer => {
if (req.headers.has('X') && this.headerAcquired == false) {
this.headerAcquired = true;
const subscription = delegate.handle(req).subscribe(event => {
if (event instanceof HttpResponse) {
this.pocessed = true;
this.requestSetter({key: this.pocessed});
this.removeRequest(req);
observer.next(event);
}
},
err => {
this.removeRequest(req);
observer.error(err);
},
() => {
this.removeRequest(req);
observer.complete();
});
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
} else {
this.requests.push(req);
this.requestGetter().subscribe(res => {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.subjectInit = true;
this.requests.splice(i, 1);
req = req.clone({ setHeaders: { 'X': 'X' } });
const subscription = delegate.handle(req).subscribe(event => {
if (event instanceof HttpResponse) {
this.pocessed = true;
this.request.next(true);
this.removeRequest(req);
observer.next(event);
}
},
err => {
this.removeRequest(req);
observer.error(err);
},
() => {
this.subjectInit = false;
this.removeRequest(req);
observer.complete();
});
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
this.request.unsubscribe();
};
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.