如何在 angular httpClient 拦截器中使用异步服务

How use async service into angular httpClient interceptor

使用Angular4.3.1和HttpClient,我需要将异步服务的请求和响应修改到httpClient的HttpInterceptor中,

请求修改示例:

export class UseAsyncServiceInterceptor implements HttpInterceptor {

  constructor( private asyncService: AsyncService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // input request of applyLogic, output is async elaboration on request
    this.asyncService.applyLogic(req).subscribe((modifiedReq) => {
        const newReq = req.clone(modifiedReq);
        return next.handle(newReq);
    });
    /* HERE, I have to return the Observable with next.handle but obviously 
    ** I have a problem because I have to return 
    ** newReq and here is not available. */
  }
}

响应有不同的问题,但我需要再次应用逻辑以更新响应。 在这种情况下,angular 指南建议如下:

return next.handle(req).do(event => {
    if (event instanceof HttpResponse) {
        // your async elaboration
    }
}

但是 "do() operator—it adds a side effect to an Observable without affecting the values of the stream".

Solution: the solution about request is shown by bsorrentino (into accepted answer), the solution about response is the follow:

return next.handle(newReq).mergeMap((value: any) => {
  return new Observable((observer) => {
    if (value instanceof HttpResponse) {
      // do async logic
      this.asyncService.applyLogic(req).subscribe((modifiedRes) => {
        const newRes = req.clone(modifiedRes);
        observer.next(newRes);
      });
    }
  });
 });

因此,如何将异步服务的请求和响应修改为httpClient拦截器?

Solution: taking advantage of rxjs

好的,我正在更新我的答案, 您不能在异步服务中更新请求或响应,您必须像这样同步更新请求

export class UseAsyncServiceInterceptor implements HttpInterceptor {

constructor( private asyncService: AsyncService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // make apply logic function synchronous
  this.someService.applyLogic(req).subscribe((modifiedReq) => {
    const newReq = req.clone(modifiedReq);
    // do not return it here because its a callback function 
    });
  return next.handle(newReq); // return it here
 }
}  

如果我答对了你的问题,你可以使用 deffer 拦截你的请求

   

module.factory('myInterceptor', ['$q', 'someAsyncService', function($q, someAsyncService) {  
    var requestInterceptor = {
        request: function(config) {
            var deferred = $q.defer();
            someAsyncService.doAsyncOperation().then(function() {
                // Asynchronous operation succeeded, modify config accordingly
                ...
                deferred.resolve(config);
            }, function() {
                // Asynchronous operation failed, modify config accordingly
                ...
                deferred.resolve(config);
            });
            return deferred.promise;
        }
    };

    return requestInterceptor;
}]);
module.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push('myInterceptor');
}]);

我认为 反应流 存在问题。 intercept 方法期望 return 一个 Observable 并且你必须 flatten 你的异步结果Observable return由 next.handle

编辑

试试这个

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return this.asyncService.applyLogic(req).mergeMap((modifiedReq)=> {
        const newReq = req.clone(modifiedReq);
        return next.handle(newReq);
    });
}

You could also use switchMap instead of mergeMap

使用 Angular 6.0 和 RxJS 6.0

在 HttpInterceptor 中进行异步操作 auth.interceptor.ts

import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/index';;
import { switchMap } from 'rxjs/internal/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {}

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

    return this.auth.client().pipe(switchMap(() => {
        return next.handle(request);
    }));

  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class AuthService {

  constructor() {}

  client(): Observable<string> {
    return new Observable((observer) => {
      setTimeout(() => {
        observer.next('result');
      }, 5000);
    });
  }
}

上面的回答好像没问题。我有相同的要求,但由于更新不同的依赖项和运营商而面临问题。我花了一些时间,但我找到了解决这个特定问题的有效方法。

如果您使用 Angular 7 和 RxJs 版本 6+ 并要求异步拦截器请求,那么您可以使用此代码,它适用于最新版本的 NgRx 存储和相关依赖项:

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

    let combRef = combineLatest(this.store.select(App.getAppName));

    return combRef.pipe( take(1), switchMap((result) => {

        // Perform any updates in the request here
        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('event--->>>', event);
                }
                return event;
            }),
            catchError((error: HttpErrorResponse) => {
                let data = {};
                data = {
                    reason: error && error.error.reason ? error.error.reason : '',
                    status: error.status
                };
                return throwError(error);
            }));
    }));

如果您需要在拦截器中调用异步函数,则可以使用 rxjs from 运算符遵循以下方法。

import { MyAuth} from './myauth'
import { from } from 'rxjs'

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: MyAuth) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // convert promise to observable using 'from' operator
    return from(this.handle(req, next))
  }

  async handle(req: HttpRequest<any>, next: HttpHandler) {
    // if your getAuthToken() function declared as "async getAuthToken() {}"
    await this.auth.getAuthToken()

    // if your getAuthToken() function declared to return an observable then you can use
    // await this.auth.getAuthToken().toPromise()

    const authReq = req.clone({
      setHeaders: {
        Authorization: authToken
      }
    })

    // Important: Note the .toPromise()
    return next.handle(authReq).toPromise()
  }
}

我在我的拦截器中使用异步方法是这样的:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    public constructor(private userService: UserService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return from(this.handleAccess(req, next));
    }

    private async handleAccess(req: HttpRequest<any>, next: HttpHandler):
        Promise<HttpEvent<any>> {
        const user: User = await this.userService.getUser();
        const changedReq = req.clone({
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'X-API-KEY': user.apiKey,
            })
        });
        return next.handle(changedReq).toPromise();
    }
}