Angular 5 + Ionic 3: I can not send headers in API requests

0

I am consuming an API through a post method and need to send in the Authorization header. I'm doing the following:

public post(resource, body, authorization = false): Observable<any> {

    const headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');

    if (authorization) {
        let token = this.userStorageService.get('accessToken');
        headers.append('Authorization', 'Bearer ' + token);
    }

    return this.http
        .post<Observable<any>>('${environment.apiUrl}${resource}', JSON.stringify(body), {headers: headers})
        .map(response => response);
}

But for some reason the Angular does not send the headers. I've tried different ways, but none works. Anyone have any idea what that might be?

OBS 1: I'm using Angular 5 and Ionic 3 OBS 2: I've tried using Interceptors and it did not work NOTE: I have already debugged the request in the api by Postman, it works right there, sending the headers and everything, but the app does not work in any way.

    
asked by anonymous 22.03.2018 / 14:41

2 answers

0

As far as I understand, HttpHeaders is immutable. Try this:

Example:

const headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');

or:

const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
    
26.03.2018 / 16:21
0

Even using append of HttpHeaders it returns a copy that should be used.

For example

const headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');

Now the variable headers contains the desired value.

I hope I have helped.

[] s

    
08.10.2018 / 17:04