3

I have a post method which is working and fetching my token from the server

authenticate() {
  let url = this.server + 'authenticate';
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });

  let body = JSON.stringify({
    'password': 'admin',
    'rememberMe': true,
    'username': 'admin'
  });
  return this._http.post(url, body, options)
    .map((res: Response) => res.json())
    .subscribe(result => this.token = result.id_token);
}

where this.server is a string having the url of the server. and this._http is just an instance of the angular Http

private _http: Http;
constructor(http: Http) {
  this._http = http;
}

and this.token is just an empty string private token: string;

Now all this is working just fine and I am getting the right token from the server. My problem is that when I try to use this token in a get method it doesn't work and I get a 401 (unauthorized) error.

My buggy get method is:

getData(src) {
  let url = this.server + src;
  let headers = new Headers({'Authorization': 'Bearer ' + this.token});
  return this._http.get(url, headers)
  .map((res: Response) => res.json())
  .subscribe(res => console.log('res'));
}

2 Answers 2

1

So the problem was that I should have added {} around the headers when I sent them. the get should be this._http.get(url, { headers })

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

Comments

1

Http.get takes a url string and an optional RequestOptionsArgs as parameters. Wrapping the header in a RequestOptions object should do the trick.

getData(src) {
  let url = this.server + src;
  let headers = new Headers({'Authorization': 'Bearer ' + this.token});
  let options = new RequestOptions({ headers: headers });
  return this._http.get(url, options)
    .map((res: Response) => res.json())
    .subscribe(res => console.log('res'));
}

4 Comments

I actually had it like that and there is no difference what so ever
add a return in the .map() call .map((res:Response => return res.json())
Thank you for you, but that wasn't the problem. I wrote the answer if you want it
Using the {} might work, but the correct way is to use a RequestOptions object. I have updated my answer to reflect this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.