【问题标题】:How to set header for HTTP in Angular2?如何在 Angular2 中为 HTTP 设置标头?
【发布时间】:2016-12-13 07:31:32
【问题描述】:

所以基本上我需要将自定义身份验证标头添加到所有引用 API 的请求。在构造函数中我想添加这个标题,然后在类方法中使用this.http

import { Injectable } from '@angular/core';

import { Config, Events } from 'ionic-angular';

import { Http } from '@angular/http';


@Injectable()

export class APIRequest {

    constructor (
        private http: Http,
        private config: Config,
    ) { 
        this.http.headers.append('My-Custom-Header','MyCustomHeaderValue');
    }
}

【问题讨论】:

  • @SabbirRahman 不,我不想在每种方法中设置标题。我需要在构造函数中设置一次。
  • 您可以创建另一个服务并在那里包装 HTTP。所以有 post, get, .... 与您的自定义标题。

标签: angular typescript ionic2


【解决方案1】:

我用这种方式对标题使用通用功能

let method = 'POST';

let requestOptions: RequestOptions = new RequestOptions({
headers: this.jsonHeaders(),
method: method
});

jsonHeaders() // 函数

public jsonHeaders(): Headers {
let headers: Headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
headers.append("Cache-Control", "no-cache");
headers.append("Cache-Control", "no-store");
headers.append("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");

if(this.token) {
headers.append('Authorization', 'Bearer ' + this.token);
}

return headers;
}

HTTP Request

let url = '/login'
this.http.request(url, requestOptions)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2016-10-15
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    相关资源
    最近更新 更多