Angular 2 : Uncaught error when returning Observable

标签 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 的页面时,我得到:

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

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

最佳答案

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

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

关于 Angular 2 : Uncaught error when returning Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39927671/

相关文章:

javascript - 为什么 'emit' 仅在我第一次单击按钮时不显示名称?

javascript - 使用 switchmap 和 forkjoin 链接 observables 不能按预期工作 angular typescript rxjs

使用 Subscribers 和 subscribe.first() 时 Angular2+ 内存泄漏

javascript - 如何在 Angular 2 中触发闹钟(在闹钟中)?

angular - ionic 3 单击按钮后从 ion-textarea 获取文本

authentication - Spring Data REST 中的 CORS 预检请求

javascript - 如何将从 json 接收到的 ko.observable 字符串解析为整数(数字)值

angular - 如何获取特定的文档ID? AngularFire 5.1.1 |云Firestore |文件

javascript - 使用 Observable 检测变量的变化

angular - 可从字符串中观察到(Angular 2)