9

im new with Angular and i'm working on a project that for some reasons i have to set headers for server side authorization, Im using Angular 4 and the HttpClient Module imported from '@angular/common/http'

This is my AuthService Class

import { Injectable } from '@angular/core';
import { User } from '../../models/user';
import { HttpClient, HttpHeaders, HttpRequest } from 
'@angular/common/http';
import { Observable } from 'rxjs';
import { Globals } from '../../utils/global';
import { Converters } from '../../utils/converters';


@Injectable()
export class AuthService {
getUserByToken(token: string): any {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('authorization', 'Bearer ' + token);

    console.log(headers);

    return new Promise((resolve, reject) => {
      this.http.get(this.global.urls['info'], { headers: headers }).subscribe((data) => {
        if (data != null) {
          this.converter.userJsonToObject(data).then((data: User) => {
            this.setCurrentUser(data);
            this.persistToken(data.token);
            resolve(data);
          });
        } else {
          reject('This user is not defined');
        }
      }, (err) => {
        reject(err);
      });
    });

  }

ARC

When i run my project and i call getUserByToken(token) function, the server console told me that no token was send. The endpoint is working perfect with ARC so the issue is on the client side. does anyone can help me to resolve this issue problem. :D

BenFarhat Souhaib
  • 340
  • 3
  • 5
  • 16
  • You are having a typo in the `authorization` in which `A` should in be upper case. Also try to use `headers.set()` instead of `append` – Aravind Dec 09 '17 at 02:32
  • by looking at my screenshot the endpoint is working fine even by taping 'authorization' anyway the issue is with the way that i'm setting the headers. even by using header.set(), still not working. – BenFarhat Souhaib Dec 09 '17 at 02:35
  • Possible duplicate of [Angular \[4.3\] Httpclient doesn't send header](https://stackoverflow.com/questions/45286764/angular-4-3-httpclient-doesnt-send-header) – Jota.Toledo Dec 09 '17 at 18:45

1 Answers1

19

It is of type immutable Map so if you assign a new value it will reinitialize the object so you should be doing as

let headers = new HttpHeaders().set('Content-Type', 'application/json')
                               .set('authorization', 'Bearer ' + token);

or

let headers = new HttpHeaders().set('Content-Type', 'application/json');
headers = headers.set('authorization', 'Bearer ' + token);
Aravind
  • 40,391
  • 16
  • 91
  • 110