0
votes

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?

2
Is there a reason you can't just use http within the API class, and not pass it in at all (that somehow looks wonky, I don't think it's a good idea to pass around an instance of an injected service...why not just inject it into the class that's going to use it)? And wouldn't you need to call API.doRequest? - Tim Consolazio

2 Answers

1
votes

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

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")