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

标签 angular typescript rxjs interceptor angular2-observables

使用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 指南建议如下所示:

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

但是“do() 运算符——它在不影响流值的情况下为 Observable 添加了副作用”。

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

那么,如何将带有async服务的request和response修改为httpClient拦截器呢?

Solution: taking advantage of rxjs

最佳答案

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

关于angular - 如何将异步服务用于 Angular httpClient 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45345354/

相关文章:

angular - 订阅可观察对象的主体

angular - 无法读取未定义错误的属性 'navigate'

typescript - AWS CDK Typescript,如何从 lambda 触发步进函数?

javascript - 指定 `keyof? 时拒绝 Typescript 泛型?

rxjs - ReactiveX 运算符 - 去抖动,但先触发,然后过滤其他运算符

Angular rxjs 订阅拆解

angular - 读取 Angular 4 防护中的查询字符串参数?

Angular2 RC1 管道总是通过未定义的

node.js - 管理由 API 补丁引起的状态更改

mongodb - 使用 ids 数组表单数据库获取所有匹配项目