首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步服务在角httpClient拦截器中的应用

异步服务在角httpClient拦截器中的应用
EN

Stack Overflow用户
提问于 2017-07-27 08:30:49
回答 7查看 21.7K关注 0票数 30

使用角4.3.1和HttpClient,我需要将异步服务的请求和响应修改为HttpInterceptor of httpClient,

修改请求的示例:

代码语言:javascript
复制
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来更新响应。在这种情况下,角度指南建议如下所示:

代码语言:javascript
复制
return next.handle(req).do(event => {
    if (event instanceof HttpResponse) {
        // your async elaboration
    }
}

但是,"do()运算符--它在不影响流的值的情况下,增加了可观察到的副作用“。

解决方案:关于请求的解决方案由bsorrentino (被接受的答案)显示,关于响应的解决方案如下:

代码语言:javascript
复制
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

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2017-07-31 11:15:33

我认为反应流存在一个问题。方法截取期望返回一个可观测的,并且您必须用next.handle返回的可观测值来平平异步结果。

尝尝这个

代码语言:javascript
复制
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

票数 15
EN

Stack Overflow用户

发布于 2019-08-29 14:14:16

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

代码语言:javascript
复制
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));
  }
}
票数 53
EN

Stack Overflow用户

发布于 2018-06-01 15:10:59

在HttpInterceptor中使用角6.0和RxJS 6.0的异步操作

auth.interceptor.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
    });
  }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45345354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档