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

Posted

技术标签:

【中文标题】如何将异步服务用于角度 httpClient 拦截器【英文标题】:How use async service into angular httpClient interceptor 【发布时间】:2018-01-02 20:41:53 【问题描述】:

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

响应的不同问题,但我需要再次应用逻辑以更新响应。 在这种情况下,角度指南建议如下:

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

【问题讨论】:

【参考方案1】:

我认为反应式流程存在问题。 intercept 方法期望返回一个 Observable,您必须使用 Observable 返回的 Observable展平您的异步结果strong>next.handle

试试这个

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,方法 flatMap()switchMap() 在我的 observable 上不可用(由 Store.slecte() 返回)。 在您的情况下,您必须将 flatMap 替换为 mergeMap【参考方案2】:

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

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

【讨论】:

【参考方案3】:

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

【讨论】:

完美运行。此外,我在 .toPromise() 之前添加了管道句柄,并且所有这些都仍然工作得很好。谢谢你。 它也适用于 Angular 11。谢谢。 它不适合我。检查***.com/questions/69665366/…【参考方案4】:

上面的答案似乎很好。我有相同的要求,但由于不同的依赖项和运算符的更新而面临问题。花了我一些时间,但我找到了解决这个特定问题的有效解决方案。

如果您使用 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);
            ));
    ));

【讨论】:

【参考方案5】:

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

【讨论】:

请解释您的代码行,以便其他用户了解其功能。谢谢! 在实时环境中不要忘记调用observer.error() 并在返回的unsubscribe() 函数中定义清理逻辑。 angular.io's Observable Guide 有一个很好的例子。【参考方案6】:

如果我的问题正确,那么您可以使用 defer 拦截您的请求

   

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

【讨论】:

延迟请求意味着您没有进行异步操作,它将停止请求执行操作然后转发它 hehehe..........推迟请求意味着将您的责任交给$q.defer 你说的是angularjs,帖子跟angular 4有关 github.com/NgSculptor/ng2HttpInterceptor/blob/master/src/app/…如果对你有帮助可以参考这篇文档 @muhammad hasnain,我在我的旧项目(angular 1.5)中使用了您建议的方法,但似乎带有 httpClient 的 angular 4 无法执行相同的功能。这个问题的目的是了解带有 httpClient 的 angular 4 是否有这个限制。【参考方案7】:

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

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
 
  

【讨论】:

我需要问题中指定的 async service 而不是您建议的 synchronous 功能。您确定这样的确认:您无法在异步服务中更新请求或响应 我很确定,因为您的请求将在您的异步服务更新时发布到服务器,同样会发生响应响应将在异步服务更改之前返回

以上是关于如何将异步服务用于角度 httpClient 拦截器的主要内容,如果未能解决你的问题,请参考以下文章

如何使角度模块忽略核心模块中添加的http拦截器

如何使用异步发布并使用 HttpClient 等待

c#:如何使用 httpclient 发布异步请求并获取流?

Angular 打字稿异步 HTTPClient 调用

如何在 C#/XAML Metro App 中使用 HttpWebRequest(或)HttpClient 进行同步服务调用?

这次使用一个最舒服的姿势插入HttpClient拦截器技能点