如何将异步服务用于角度httpClient拦截器

Pas*_*ale 8 interceptor rxjs typescript angular2-observables angular

使用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. */
  }
}
Run Code Online (Sandbox Code Playgroud)

响应的问题不同,但我需要再次使用apply来更新响应.在这种情况下,角度指南建议如下:

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

但是"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);
      });
    }
  });
 });
Run Code Online (Sandbox Code Playgroud)

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

解决方案: 利用rxjs

yot*_*ain 35

如果您需要在拦截器中调用异步函数,则可以使用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()
  }
}
Run Code Online (Sandbox Code Playgroud)

  • .toPromise() 已弃用,因此请使用 `return wait lastValueFrom(next.handle(req));` (2认同)
  • authToken 变量在哪里以及如何分配? (2认同)

bso*_*ino 8

我认为有关反应流的问题.该方法拦截预计将返回一个可观察,你必须扁平化与您的异步结果可观察到由返回next.handle

试试这个

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

您也可以使用switchMap而不是flatMap


Vol*_* Kr 6

使用 Angular 6.0 和 RxJS 6.0

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

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

  }
}
Run Code Online (Sandbox Code Playgroud)

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);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 请解释您的代码行,以便其他用户可以理解其功能。谢谢! (3认同)

Ken*_*sen 5

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

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)