How use async service into angular httpClient interceptor

前端 未结 7 889
轻奢々
轻奢々 2020-12-09 18:53

Using Angular 4.3.1 and HttpClient, I need to modify the request and response by async service into the HttpInterceptor of httpClient,

Example for modifying the requ

相关标签:
7条回答
  • 2020-12-09 19:35

    Asynchronous operation in HttpInterceptor with Angular 6.0 and 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);
        });
      }
    }
    
    0 讨论(0)
提交回复
热议问题