如何追加标题angular 4服务?

时间:2018-02-19 20:23:40

标签: angular

我的角度4服务文件我有几个HTTP调用。所有这些电话都有不同的秘密密码。但它们也有一组通用的标题信息。有人可以告诉我如何通过这些常见标题而不必重复它们。我的示例代码如下:

private getHeadersOne() {
        let headers = new Headers();
        headers.append('cache-control', 'no-cache');
        headers.append('content-type', 'application/json');
        headers.append('secret-apikey', 'abcd');
        return headers;
    }
    private getHeadersTwo() {
        let headers = new Headers();
        headers.append('cache-control', 'no-cache');
        headers.append('content-type', 'application/json');
        headers.append('secret-apikey', 'hijk');
        return headers;
    }
    private getHeadersThree() {
        let headers = new Headers();
        headers.append('cache-control', 'no-cache');
        headers.append('content-type', 'application/json');
        headers.append('secret-apikey', '1234');
        return headers;
    }

感谢您的帮助。

A

2 个答案:

答案 0 :(得分:1)

您可以使用HTTPInterceptors,这是首选方式。但如果你想要一个快速解决方案,你可以这样做:

private readonly headers = new HttpHeaders({
  "secret-apikey": "hijk",
  "content-type": "application/json",
  "cache-control": "no-cache"
});

private getSomething() {
    return this.http.get("url", { headers: this.headers });
}

private postSomething() {
    return this.http.get("url", { headers: this.headers });
}

答案 1 :(得分:0)

您可以使用此处所述的HttpInterceptor https://theinfogrid.com/tech/developers/angular/building-http-interceptor-angular-5/并稍微重构您的代码:

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';


@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor() { }

  private commonHeaders(): HttpHeaders {
    let headers = new HttpHeaders();
    headers.append('cache-control', 'no-cache');
    headers.append('content-type', 'application/json');
    return headers;
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    console.log("intercepted request ... ");

    let headers = this.commonHeaders();
    // add logic here to pick the appropriate apiKey depending on your business logic 
    headers.append('secret-apikey', "apiKey");

    // Clone the request to add the new header.
    const authReq = req.clone({ headers: headers });

    console.log("Sending request with new header now ...");

    //send the newly created request
    return next.handle(authReq)
      .catch((error, caught) => {
        //intercept the respons error and displace it to the console
        console.log("Error Occurred");
        console.log(error);
        //return the error to the method that called it
        return Observable.throw(error);
      }) as any;
  }
}