0

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?

2
  • I think this would have to be refactored so that getUser() itself returns a Promise. You'd place the authService call inside a Promise, with a then that executes the rest of your code. Commented Jun 26, 2017 at 0:27
  • getToken() is a web service? it invokes a http request Commented Jun 26, 2017 at 1:07

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. The problem is that this.authService.getToken() is of type String and therefore I can't use any methods such us subscribe, for instance. I'm trying to invoke getUser right after authorization with Facebook, and it seems that it takes a moment between logging in and AuthService to be ready to deliver data :/
hmmm, another approach is like you say, implement getUser after collect token AND wrap this authService.getToken method with some promise implementation. Is that method yours, right ?

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.