【问题标题】:Angular 2: Uncaught error when returning ObservableAngular 2:返回 Observable 时未捕获的错误
【发布时间】:2016-10-08 01:07:37
【问题描述】:

我有以下代码:

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 未授权 URL 的响应: http://localhost:4200/api/auth/validate_token

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

【问题讨论】:

    标签: angular observable


    【解决方案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 有两个参数。第一个是成功案例,第二个是错误案例。

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2017-06-10
      • 2016-10-25
      相关资源
      最近更新 更多