[英]Angular HTTP Client Interceptor not working when returning custom Observable
僅供參考此問題與Angular Universal有關
我目前正在嘗試創建一個HttpClient攔截器,該攔截器緩存GET請求並以可觀察的方式返回緩存的響應。
我試圖在這里角攔截器設置為指導以下https://github.com/angular/angular/blob/master/aio/content/guide/http.md ,但我似乎無法得到它的工作,當我返回除了next.handle()以外,其他可觀察到的訂閱都不會被觸發。
這是一個矮子,演示它不起作用。 https://plnkr.co/edit/QzVpuIoj3ZFXgHm7hVW2?p=preview
攔截器示例:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// if this is cached, return the cached response.
return Observable.of({body: 'Test'});
return next
.handle(customReq)
.do((ev: HttpEvent<any>) => {
if (ev instanceof HttpResponse) {
// Cache this response
}
});
}
任何幫助將不勝感激。
我的最終目標是使此功能與NG Universal的傳輸模塊一起使用。 如果我在攔截器中解決了這個問題,那么我應該已經全部准備好了。
編輯:我的假設是錯誤的。 Angular HttpClient Interceptor Caching示例工作得很好,對於我來說,它一定是Angular Universal。 (我用Angular的工作示例更新了Plunker,以證明它適用於這種情況)。
這是我用於Angular Universal的攔截器。
constructor(private state: TransferState) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.method !== "GET") {
return next.handle(request);
}
const STATE_KEY = makeStateKey(request.urlWithParams);
const cachedResponse = this.state.get(STATE_KEY, null);
if (cachedResponse) {
return Observable.of(cachedResponse);
}
return next.handle(request).do(event => {
if (event instanceof HttpResponse) {
this.state.set(STATE_KEY, event.clone());
}
});
}
我不確定,這可能是TransferState服務的某種計時問題。
我知道了 這是有道理的,但我不敢相信我花了這么長時間才意識到這個小問題。 當我返回Observable的cachedResponse時,我需要創建一個新的HttpResponse對象,因為它是一個類,而不僅僅是一個接口。 因此像這樣:
return Observable.of(new HttpResponse<any>(cachedResponse));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.