3

I have the following piece of code:

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Angular2TokenService } from 'angular2-token';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private _tokenService: Angular2TokenService,
    private router: Router) {}

  canActivate():Observable<boolean>|boolean {
    return this._tokenService.validateToken().map(res => {
      return res.json().success;
    });
  }
}

When I load my page that goes through AuthGuard, I get:

Uncaught (in promise): Response with status: 401 Unauthorized for URL: http://localhost:4200/api/auth/validate_token

The 401 status is expected. What I don't understand is how to simply get my canActivate() function to return false when the response is 401. How can I do this?

Deendayal Garg
  • 5,030
  • 2
  • 19
  • 33
Jason Swett
  • 43,526
  • 67
  • 220
  • 351

1 Answers1

1

Here's how I ultimately ended up handling it:

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Angular2TokenService } from 'angular2-token';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private _tokenService: Angular2TokenService,
    private router: Router) {}

  canActivate():Observable<boolean>|boolean {
    return Observable.create(observer => {
      this._tokenService.validateToken().subscribe(res => observer.complete(), err => {
        this.router.navigate(['/sign-in']);
        observer.next(false);
      });
    });
  }
}

The significant thing is that my subscribe has two arguments. The first is the success case and the second is the error case.

Jason Swett
  • 43,526
  • 67
  • 220
  • 351