0

I'm trying to hit an API to do a pretty simple get request but the options doesn't seem to be getting supplied as I'm getting an authentication error, even though the same auth token works on Postman. Here's the code:

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



@Injectable()
export class UsersService {

  private nearby_url: string = APP_CONFIG.apiEndpoint + '/users/closest/';
  private me_url: string = APP_CONFIG.apiEndpoint + '/users/me/';
  private conversations_url: string = APP_CONFIG.apiEndpoint + '/users/conversations/';

  constructor(private http: HttpClient) { }

  createAuthorizationHeader() {
    var headers = new HttpHeaders();
    // get auth token

    // append auth token to headers
    headers.append("Authorization", 'Token xxxxxxxxxxxyyyyyyyyyyyyzzzzzzzzz');

    return headers
  }

  getPersonResponse(url): Observable<PersonResponse> {
    const options = {
      headers: this.createAuthorizationHeader()
    };

    return this.http.get(url, options)
      .map((response: Response) => response)
      .catch((error: any) => Observable.throw(error.error || 'Server error'));
  }

  getNearby(): Observable<PersonResponse> {
    return this.getPersonResponse(this.nearby_url);
  }

  getMe(): Observable<PersonResponse> {
    return this.getPersonResponse(this.me_url);
  }

  getConversations(): Observable<PersonResponse> {
    return this.getPersonResponse(this.conversations_url);
  }

}

What am I doing wrong here?

0

1 Answer 1

5

change to something like

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

Notice that we are building the HTTPHeaders 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.

More on the same - https://rahulrsingh09.github.io/AngularConcepts/services

Sign up to request clarification or add additional context in comments.

4 Comments

Lifesaver, thank you!
append works too.
append used to work for old Headers after the introduction of HttpClient we cannot use append @manishkumar
ill try it . Thanks for updating.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.