0
votes

Update If I amend my api to retunr res.status(200) instead of res.status(401) then I get my code to work. Im guessing the unhandled error is because I return a 401, but how can I catch and use the 401 if I get boolean error adding .catch to my .map?

Im trying to make a auth guard. My method is to request an api that does some work on the server side and returns a json body with some user information and status true, or a status of false if the webtoken cannot be verified

In my angular code I have

canActivate() {
return this.http.get(`http://localhost:3000/api/user/status`, options)
  // return this.http.get(`/api/user/status`, options)
  .map(res => {
    if(!res){
      this.router.navigate(['/login']);
      return false;
    }
    let user: any = res.json();
    return true;
  })
}

If I run my code with a correct token I get the page authenticating. If I amend the token my POSTMAN test return a status: false but when I use my website I get errors saying that I have unhandled errors.

So I try to add a catch

.catch(e => {
    this.router.navigate(['/login']);
      return false;
  })

but I get compile errors saying " Argument of type '(e: any) => boolean' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput'. Type 'boolean' is not assignable to type 'ObservableInput'.)"

Any advice?

1

1 Answers

0
votes

I was using

.catch(e => {
    this.router.navigate(['/login']);
      return false;
  })

but the Observable in CanActivate requires a boolean which can be passed with

.catch(e => {
    this.router.navigate(['/login']);
      return Observable.of(false);
  })