Jakub
Jakub

Reputation: 187

How to wait for asynchronous data before returning http.get

I'm using ng2-ui-auth for my front-end and I've stumbled upon an issue I have no idea how to fix... This is a simple method from my UserService but there's a catch - an asynchronous method is being invoked to get one, necessary token for the http.get call.

getUser()
{
  const headers: Headers = new Headers();
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');
  headers.append('X-Auth-Token', this.authService.getToken());

  const options = new RequestOptions({headers: headers});

  return this.http.get('http://localhost:9900/user', options).map(response => response.json());
}

The problem is - sometimes the http.get is being called before this.authService.getToken returns the data, so I end up with a null in 'X-Auth-Token', thus leaving me an 'Unauthorized' error.

Is there any way to wait until the header is complete and then return http.get?

Upvotes: 0

Views: 582

Answers (1)

Dody
Dody

Reputation: 668

Try using promises and method Then() to collect the response. Such like this:

getUser()
{
  const headers: Headers = new Headers();
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');

  //Collect token value
  this.authService.getToken().then(function(resp){
      headers.append('X-Auth-Token', resp);
  });

  const options = new RequestOptions({headers: headers});

  return this.http.get('http://localhost:9900/user',options).map(response => response.json());
}

Upvotes: 1

Related Questions