Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Uncaught error when returning Observable

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?

like image 434
Jason Swett Avatar asked Jul 19 '26 02:07

Jason Swett


1 Answers

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.

like image 99
Jason Swett Avatar answered Jul 20 '26 22:07

Jason Swett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!