簡體   English   中英

Angular HttpInterceptor-處理異步響應

[英]Angular HttpInterceptor - Handle with async response

我正在編寫使用IndexedDB緩存數據的Angular應用程序。

每當應用程序要對服務器進行特定的http調用時,我都希望從IndexedDB中檢索此數據並充實或替換服務器的響應。

問題是從IndexedDB檢索數據是異步操作,該操作返回Observable,而我無法將修改后的數據返回給調用服務。

攔截器如下所示:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  return next.handle(req).map((event) => {
    if (event instanceof HttpResponse) {
      console.log("before cacheResponseProccess");

      const val: Observable<HttpEvent<any>> = this.angularCache.cacheResponseProccess(event);

      val.subscribe(x => {
        console.log('Return modified response is:');
        console.log(x);
        return x;
      });
    }
  }).catch((error, caught) => {
    return Observable.throw(error);
  });
}

請在https://stackblitz.com/edit/angular-owqgb6上查看問題樣本

您需要在map運算符中返回內容( 在異步回調中返回值實際上不會將它們返回到外部函數 )。 另外,當您獲取異步結果以替換原始HttpResponse時,可以將map更改為mergeMap運算符,並在其中返回一個Observable。

請嘗試以下代碼示例:

return next.handle(req).mergeMap((event) => {   // use mergeMap instead of map
  return new Observable(ob => {                 // return new Observable to retrieve asynchronous data
    if (event instanceof HttpResponse) {
      console.log("before cacheResponseProccess");

      const val: Observable<HttpEvent<any>> = this.angularCache.cacheResponseProccess(event);

      val.subscribe(x => {
        console.log('Return modified response is:', x);
        ob.next(x);         // return modified result
      });
    }
  });
}).catch((error, caught) => {
  return Observable.throw(error);
});

固定演示

您可以執行以下操作:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  if (req.url.indexOf('https://api.someurl.com/') > -1) {
    let authReq: HttpRequest<any> = req;

    return this.authService.getCurrentSession().pipe(
      mergeMap(
        (session: Session) => {
          const token: string = session.getToken();
          authReq = req.clone({
            headers: req.headers.set('Authorization', token)
          });
          return next.handle(authReq);
        }
      ), 
      catchError(
        (error) => {
          console.error('Intercept error, couldn\'t add authorisation headers', error.message);
          next.handle(authReq);
          return of(error);
        }
      )
    );
  } else {
    return next.handle(req);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM