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?

halsdunes
  • 1,199
  • 5
  • 16
  • 28

1 Answers1

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

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86