0

There's a really good chance I don't know what I'm talking about here, and perhaps I'm doing this all wrong. Hopefully someone with far more web knowledge than me can point me in the right direction.

I built a very simple Angular2 service that returns promises and issues web requests.

Here's an example:

postAddUser(username, password, email): Promise < SimpleAppARenoAPITokenResponse > {
  return this.http.post(this.rpcUrl, JSON.stringify(this.makeAddUser(username, password, email)), {
      headers: this.headers
    })
    .toPromise()
    .then(res => res.json() as SimpleAppARenoAPITokenResponse)
    .catch(this.handleError);
}

Then in the handleError I've been checking for the "error.status" of 401, if it is I'd like to redirect to the /login page. For that I'm doing:

private handleError(error: Response | any) {
  // In a real world app, we might use a remote logging infrastructure
  let errMsg: string;
  console.log(error);
  if (error.status == 401) {
    console.log('gets here');
    this.router.navigatebyUrl('/login');
  }
}

Now I get a 'gets here' in the console, but it's like nothing happens when I call the router command. I've injected router and route into the service and that seems to work, just can't figure out how to redirect during the catch.

If I call navigatebyUrl in the postAddUser function it works fine. My guess is it has something to do with Promises inside Promises or the like. However I'm still struggling to understand all this with my dinosaur win32 brain.

Thanks for any suggestions you could provide.

n00dl3
  • 21,213
  • 7
  • 66
  • 76
OldSchool
  • 152
  • 9
  • 1
    Howdy, coderosaurus rex ! Use `.catch(this.handleError.bind(this));` or `.catch((err)=>this.handleError(err));`. Cheers. – n00dl3 Apr 14 '17 at 13:40
  • I guess you have an error with this line : `.then(res => res.json() as SimpleAppARenoAPITokenResponse)` and you don't republish your code. Check your console and then replace it with `.then(res => res.json())` – Karbos 538 Apr 14 '17 at 14:03
  • n00dl3, that was it! Thank you so much. I assume I needed to pass the "this" in so it knew the object context. How do I mark your comment as the answer? – OldSchool Apr 14 '17 at 14:36
  • @OldSchool Instead accept the duplicate that n00dl3 marked this question with :) – AT82 Apr 14 '17 at 15:18

0 Answers0