typescript 如何将异步服务用于Angular httpClient拦截器

ni65a41a  于 2023-05-19  发布在  TypeScript
关注(0)|答案(8)|浏览(107)

使用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. */
  }
}

响应的问题不同,但我需要再次applyLogic以更新响应。在这种情况下,角向导建议如下:

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

ymdaylpp

ymdaylpp1#

如果你需要在拦截器中调用一个异步函数,那么可以使用rxjsfrom操作符来执行以下方法。

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));
  }
}
czq61nw1

czq61nw12#

我认为有一个关于React流的问题。方法intercept期望返回一个 Observable,你必须用next.handle返回的 Observable 来 * flatten* 你的异步结果
试试这个

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

4dc9hkyq

4dc9hkyq3#

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

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

h7wcgrx34#

HttpInterceptor与Angular 6.0和RxJS 6.0的异步操作
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);
    });
  }
}
w46czmvw

w46czmvw5#

上面的答案似乎很好。我有相同的要求,但面临的问题,由于更新不同的依赖关系和运营商。花了我一些时间,但我找到了一个解决这个具体问题的工作方案。
如果你使用的是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);
            }));
    }));
1dkrff03

1dkrff036#

这是我在Angular 15中的解决方案,它是我需要修改所有响应的地方。张贴,因为它花了我更长的时间比我想承认,为了让这个工作。
我使用Nswag在API端生成请求/响应类型和Mediatr。我有一个带有success & proceed bools的通用响应类。每个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;
    })));
  }
}
wqlqzqxt

wqlqzqxt7#

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

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

pgx2nnw88#

如果我得到你的问题比你可以拦截您的请求使用延迟

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');
}]);

相关问题