RobinJ
RobinJ

Reputation: 5253

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. For these requests to work, I need certain headers to be added to every request I make to the API (including a JWT header).

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.

As it turns out, however, I cannot use the Http class from my API class, as it will come up with the following error; error

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

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.

Is there a way to fix this, or perhaps a better way to achieve the desired result? Should I just extend Http?

Upvotes: 0

Views: 3277

Answers (2)

user3025289
user3025289

Reputation:

That's the way today setting HTTP headers (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. This is because HttpHeaders is immutable, and its API methods do not cause object mutation.

Instead, a call to set will return a new HttpHeaders object containing the new value properties. So this means that the following will NOT work:

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

Upvotes: 0

Aravind
Aravind

Reputation: 41563

You should be using append() method to add headers and then pass it to request object as below

 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) => { ... } );
    }

Upvotes: 1

Related Questions