Angular2身份验证 - 键入&#39; AsyncSubject&lt; {}&gt;&#39;不能分配类型&#39; AsyncSubject <boolean> - observables和typescript

时间:2016-07-05 14:37:13

标签: javascript authentication typescript angular angular2-routing

我是观察者和打字稿的新手,所以我搞砸了一些东西。这是我对angular2

的身份验证组件
// route-protection.service.ts
import {Injectable} from '@angular/core';
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import {Observable} from 'rxjs';


/*
 * Shared Utilities
 */
import {Authentication} from './authentication.service';
import {Logging} from '../../app-components/common/utility';

@Injectable()
export class RouteProtection implements CanActivate {

  constructor(private authService:Authentication,
              private router:Router) {

  }


  canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot):boolean {
    return this.authService.checkAuth()
      .map(e=> {
        if (e) {
          return true;
        }
      }).catch(()=> {
        this.router.navigate(['/about'])
        return Observable.of(false)
      })
  }
}

但是我收到了这个错误:

[default] ~/src/app-components/common/route-protection.service.ts:20:3 
    Type 'AsyncSubject<{}>' is not assignable to type 'AsyncSubject<boolean>'.
  Type '{}' is not assignable to type 'boolean'.
[default] ~/src/app-components/common/route-protection.service.ts:29:12 
    Type 'Observable<boolean>' is not assignable to type 'boolean'.

这是什么意思?我正在尝试使用angular2并添加路线保护&#39;所以路由只能在认证完成后激活。

1 个答案:

答案 0 :(得分:2)

此方法返回Observable<boolean>而不是普通boolean

  canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean> {

CanActivate的实际签名是

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean>|boolean

这意味着两者都被允许但您的代码实际返回Observable<boolean>

相关问题