Angular 2:返回Observable时出现未捕获的错误

时间:2016-10-08 01:07:37

标签: angular observable

我有以下代码:

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;
    });
  }
}

当我加载遍历AuthGuard的网页时,我得到:

  

未捕获(承诺):状态响应:401网址未经授权:   http://localhost:4200/api/auth/validate_token

预计401状态。我不明白的是,当响应为401时,如何简单地让canActivate()函数返回false。我该怎么做?

1 个答案:

答案 0 :(得分:1)

以下是我最终处理它的方式:

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);
      });
    });
  }
}

重要的是我的subscribe有两个参数。第一个是成功案例,第二个是错误案例。