代码之家  ›  专栏  ›  技术社区  ›  39ro

Interceptor Angular 4.3-在克隆请求上设置多个标头

  •  31
  • 39ro  · 技术社区  · 7 年前

    我只是注意到 Header Object

    这是 new Interceptor 逻辑:

    // Get the auth header from the service.
    const authHeader = this.auth.getAuthorizationHeader();
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    

    例子:

    headers?: HttpHeaders;
    
        headers: req.headers.set('token1', 'asd')
    

    setHeaders?: {
       [name: string]: string | string[];
    };
    
        setHeaders: {
                 'token1': 'asd',
                 'token2': 'lol'
        }
    

    如何在此请求中有条件地添加多个标头?

     myLovellyHeaders(headers: Headers) {
        headers.set('token1', 'asd');
        headers.set('token2', 'lol');
         if (localStorage.getItem('token1')) {
         headers.set('token3', 'gosh');
         }
        }
        const headers = new Headers();
        this.myLovellyHeaders(headers);
    
    4 回复  |  直到 7 年前
        1
  •  25
  •   non4me    7 年前

    角度4.3+

    在侦听器中设置多个标头:

    import {
      HttpEvent,
      HttpInterceptor,
      HttpHandler,
      HttpRequest,
      HttpHeaders
    } from '@angular/common/http';
    import {Observable} from 'rxjs/Observable';
    
    import {environment} from '../../../../environments/environment';
    
    export class SetHeaderInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
        const headers = new HttpHeaders({
          'Authorization': 'token 123',
          'WEB-API-key': environment.webApiKey,
          'Content-Type': 'application/json'
        });
    
    
        const cloneReq = req.clone({headers});
    
        return next.handle(cloneReq);
      }
    }
    
        2
  •  15
  •   Enayat    6 年前

    headers: req.headers.set('token1', 'asd')
    .set('content_type', 'asd')
    .set('accept', 'asd')
    
        3
  •  12
  •   Max Koretskyi    6 年前

    新的HTTP客户端使用不可变头对象。您需要存储对之前标头的引用以改变对象:

     myLovellyHeaders(headers: Headers) {
         let p = headers.set('token1', 'asd');   
         p = p.set('token2', 'lol');
         if (localStorage.getItem('token1')) {
            p = p.set('token3', 'gosh');
         }
    

    看见 Why HttpParams doesn't work in multiple line in angular 4.3 了解为什么需要存储对返回值的引用。

    标题也是这样:

    export class HttpHeaders {
      ...
      set(name: string, value: string|string[]): HttpHeaders {
        return this.clone({name, value, op: 's'});
      }
    
      private clone(update: Update): HttpHeaders {
        const clone = new HttpHeaders();
        clone.lazyInit =
            (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
        clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
        return clone;
      }
    

    要了解更多拦截器背后的机制,请阅读:

        4
  •  8
  •   Alex    6 年前

    export class TokenInterceptor implements HttpInterceptor {
    
        constructor() { }
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
            let headers = request.headers
                .set('Content-Type', 'application/json')
                .set('Authorization', `Bearer ${sessionStorage.getItem('authToken')}`);
    
            const cloneReq = request.clone({ headers });
    
            return next.handle(cloneReq);
        }
    }