简体   繁体   English

Angular 2中针对每个请求的自定义Http标头

[英]Custom Http headers in Angular 2 for every request

In my Angular 2 application, I'm trying to use Http ( @angular/http ) to make requests to my API. 在我的Angular 2应用程序中,我试图使用Http@angular/http )向我的API发出请求。 For these requests to work, I need certain headers to be added to every request I make to the API (including a JWT header). 为了使这些请求正常工作,我需要将某些标头添加到对API提出的每个请求中(包括JWT标头)。

What I'd like to do is have an API class that takes care of creating the Http requests and some error handling and validation etc. 我想做的是拥有一个API类,该类负责创建Http请求以及一些错误处理和验证等。

As it turns out, however, I cannot use the Http class from my API class, as it will come up with the following error; 但是事实证明,我无法使用API类中的Http类,因为它会出现以下错误; 错误

user.service.ts user.service.ts

import { Injectable } from '@angular/core';
import {User} from "../models/User";
import {API} from "../API";
import {Http} from "@angular/http";

@Injectable()
export class UserService
{
    constructor (private http : Http) {}

    getProfile (user : User)
    {
        let api = new API (this.http);

        return api.doRequest ('/user/' + user.id + '/profile');
    }
}

API.ts API.ts

import {Http, Headers, RequestOptions} from '@angular/http';

export class API
{
    ...

    constructor (private http : Http) {}

    doRequest (url : string, method : string, data?)
    {
        let headers = {...};
        let options = new RequestOptions ({ headers: new Headers (headers), ... } );

        return this.http.get (url, data, options)
            .catch ((error) => { ... } );
    }
}

Things work better when using Http straight from the UserService , however. 直接从UserService使用Http时,情况会更好。

Is there a way to fix this, or perhaps a better way to achieve the desired result? 有没有办法解决这个问题,或者有更好的方法来达到预期的效果? Should I just extend Http ? 我应该只扩展Http吗?

You should be using append() method to add headers and then pass it to request object as below 您应该使用append()方法添加标头,然后将其传递给请求对象,如下所示

 doRequest (url : string, method : string, data?)
    {
        headers= new Headers();
        headers.append(name1,value1);
        headers.append(name2,value2);
        ....
        let options = new RequestOptions ({ headers: headers, ... } );

        return this.http.get (url, data, options)
            .catch ((error) => { ... } );
    }

That's the way today setting HTTP headers (Angular > 4): 今天就是这样设置HTTP标头(Angular> 4)的方式:

Import: 进口:

import {HttpClient, HttpHeaders} from '@angular/common/http';

and usage: 和用法:

const headers = new HttpHeaders()
    .set("X-CustomHeader", "custom header value");

Notice that we are building the headers object by chaining successive set() methods. 注意,我们通过链接连续的set()方法来构建标头对象。 This is because HttpHeaders is immutable, and its API methods do not cause object mutation. 这是因为HttpHeaders是不可变的,并且其API方法不会导致对象突变。

Instead, a call to set will return a new HttpHeaders object containing the new value properties. 相反,对set的调用将返回一个包含新value属性的新HttpHeaders对象。 So this means that the following will NOT work : 因此,这意味着以下操作将无效

const headers = new HttpHeaders ();
headers.set("X-CustomHeader", "custom header value")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM