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

35

使用Angular 4.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指南建议像这样做:

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

但是,“do()操作符会在不影响流值的情况下向Observable添加副作用”。

解决方案:关于请求的解决方案由bsorrentino(在被接受的答案中)提供,关于响应的解决方案如下:

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拦截器中?

解决方案:利用rxjs优势。

8个回答

66

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

import { MyAuth} from './myauth'
import { from, lastValueFrom } 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
      }
    })

    return await lastValueFrom(next.handle(req));
  }
}

它运行得非常完美。此外,我在 .toPromise() 之前添加了管道句柄,一切仍然很棒。谢谢你。 - GianPierre Gálvez
它也可以与Angular 11一起使用。谢谢。 - Dash
它对我不起作用。请查看 https://dev59.com/xGoMtIcB2Jgan1znmLjP#69665906?noredirect=1#comment123141308_69665906 - Gabriel García Garrido
2
.toPromise()已被弃用,请使用return await lastValueFrom(next.handle(req)); - Lucas Vellido
2
authToken变量在哪里和如何赋值? - Abraham Putra Prakasa

15
我认为关于“响应式流”存在一个问题。方法“intercept”希望返回一个“Observable”,您需要使用“next.handle”返回的“Observable”来“展开”您的异步结果。
尝试这个。
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);
    });
}

你也可以使用switchMap代替mergeMap


我正在使用Angular 8,但是我的observable(由Store.select()返回)上没有可用的flatMap()switchMap()方法。 - Ahmad Shahwan
在您的情况下,您需要使用mergeMap替换flatMap - bsorrentino

7
我在我的拦截器中使用了一个异步方法,如下所示: ```

我在我的拦截器中使用了一个异步方法,如下所示:

```
@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();
    }
}

6

使用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);
    });
  }
}

3
请解释你的代码行,以便其他用户理解其功能。谢谢! - Ignacio Ara
在实时环境中,不要忘记调用 observer.error() 并在返回的 unsubscribe() 函数中定义清理逻辑。在 angular.io 的 Observable Guide 中有一个很好的例子。 - webpreneur

1
上面的答案似乎很好。我有同样的要求,但由于不同依赖项和运算符的更新而遇到了问题。花了一些时间,但我找到了一个适用于这个特定问题的可行解决方案。
如果您正在使用Angular 7和RxJs版本6+,并且需要使用Async Interceptor请求,则可以使用此代码,该代码适用于最新版本的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);
            }));
    }));

0

这是我在Angular 15中的解决方案,用于修改所有响应。 发布它花费了我比我愿意承认的时间来使其正常工作。

我使用Nswag生成请求/响应类型,并在API端使用Mediatr。 我有一个通用的响应类,包含成功和进行布尔值。每个API调用都会返回这些值。这种设置使我能够拥有很多控制权,并且在使用toastr时使错误处理更加整洁。

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpStatusCode } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Utilities } from "somewhere";
import { ToastrService } from "ngx-toastr";
import { from, lastValueFrom, map } from "rxjs";

@Injectable()
export class ResponseHandlerInterceptor implements HttpInterceptor {
  constructor(public toastrService: ToastrService) { }

  intercept(req: HttpRequest<unknown>, next: HttpHandler) {
    return from(this.handle(req, next));
  }

  async handle(request: HttpRequest<any>, next: HttpHandler) {

    debugger;
    // request logic here, no access to response yet. 
    if (request.url == '/assets/config.dev.json') {

      // await async call
      let config = await lastValueFrom(Utilities.someFunctionWhichReturnsObservable());

      // can modify request after async call here, like add auth or api token etc.

      const authReq = request.clone({
        setHeaders: {
          Authorization: config.API_Token
        }
      })
    }

    return await lastValueFrom(next.handle(request).pipe(map(async response => {

      //response logic here, have access to both request & response

      if (response instanceof HttpResponse<any> && response.body instanceof Blob && response.body.size > 0) {

        // await async call
        let responseBody = await lastValueFrom(Utilities.readFile(response.body)) as string;

        //can modify response or do whatever here, i trigger toast notifications & possibly override status code 

        if (request.url.includes('/api/') && response.body.type === "application/json") {
          let genericResponse = JSON.parse(responseBody) as IGenericResponse<any>;

          if (genericResponse.success == false) {
            if (genericResponse.proceed == false) {
              this.toastrService.error(genericResponse.errorMessage, null, { progressBar: true, timeOut: 29000 });

              let responseOverride = {
                ...response,
                status: HttpStatusCode.InternalServerError
              }

              return responseOverride as HttpEvent<any>;
            }
          }
        } else if (response.body.type === "text/plain") {
          console.log(responseBody);
        }

      }

      return response;
    })));
  }
}


-2

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

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
 }
}  

我需要根据问题中指定的异步服务,而不是您提出的同步函数。您确定这个说法吗:“您无法在异步服务中更新请求或响应”? - Pasquale Vitale
我非常确定,因为当您的异步服务更新服务器时,您的请求将被发布到服务器,同样的情况也会发生在响应上,即在异步服务更改响应之前,响应将被返回。 - Ghulam Mohayudin

-5

如果我理解你的问题正确,那么你可以使用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');
}]);


推迟请求意味着您不进行异步操作,它会停止请求执行该操作,然后将其转发。 - Ghulam Mohayudin
推迟请求意味着将您的责任交给$q.defer。 - muhammad hasnain
3
你在谈论AngularJS,这篇文章与Angular 4相关。 - Pasquale Vitale
你可以参考这个文档,如果有帮助的话。https://github.com/NgSculptor/ng2HttpInterceptor/blob/master/src/app/http.interceptor.ts - muhammad hasnain
@muhammad hasnain,我在我的旧项目(angular 1.5)中使用了您建议的方法,但似乎使用httpClient的angular4无法实现相同的功能。这个问题的目的是了解angular4是否有此限制。 - Pasquale Vitale
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接