[英]angular http interceptor - abort response
有沒有辦法使用 angular 的 http 攔截器來攔截響應,並有點刪除它/扔掉它,這樣未來的下游回調就不會被執行?
我希望它的行為不會執行任何 console.log。
this.http.get('/foo').subscribe(
data => console.log("success", data),
err => console.log("fail.", err)
);
我見過修改響應的示例,或者用 null 或其他一些標記值替換響應,但我寧願不這樣做,因為那樣我的所有成功/失敗處理程序都必須尋找標記,這降低了使用攔截器來處理某些響應。
我有一種感覺,這更像是一個 rxjs 問題,而不是一個角度攔截器問題,但我對 rx 還不夠熟悉,尚不確定。
如果重要,我正在使用 angular 5.1
您可以使用Observable.empty
來完成流而不發出任何數據。 要將其與HttpInterceptor
結合, HttpInterceptor
其鏈接到next.handle
:
return next.handle(req).switchMap(() => Observable.empty());
我不知道如何用Promise
做到這一點,抱歉。
我發現了另一種方法可以防止 subscribe() 回調被調用。 這是一個示例攔截器,如果 HttpResponse 中存在某個 http 標頭,它將避免調用下游訂閱者。
但是請注意,這種方法並沒有真正“丟棄響應”。 相反,它會無限期地延遲響應。 如果您有使用計時器的代碼(例如,如果在 60 秒內未收到成功或錯誤響應,則某些代碼會出錯),這可能是一個問題,因為這正是該方法的工作原理 - 它只是從不響應。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
switchMap((event: HttpEvent<any>) => {
// In this example, I only care about checking valid http responses.
// But, if you also want to inspect errors, you might consider checking for HttpResponseBase or HttpErrorResponse
if (event instanceof HttpResponse) {
// Check if this response has a certain http response header set.
// If so, we throw the response away.
if (event.headers.has('my-custom-header')) {
// We intentionally return an Observable that will never complete. This way,
// downstream subscribers will never receive anything, and any .toPromise()
// conversions that may be present will also never be invoked because toPromise() only
// gets invoked when the Observable completes.
// It doesn't actually throw the response away, but rather, it makes the subscribers wait forever, so they will never get a response.
// Be careful if you use timeouts.
return new Subject<HttpEvent<any>>();
}
}
// The default case - we pass the response back through unmodified.
return Observable.of(event);
})
);
}
// These console.logs will not be called
this.http.get('/foo').subscribe(
data => console.log("success", data),
err => console.log("fail.", err)
);
// Neither will these
this.http.get('/foo').toPromise(
data => console.log("success", data),
err => console.log("fail.", err)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.