2

我是新的observables和打字稿,所以我搞砸了。下面是angular2Angular2身份验证 - 类型'AsyncSubject <{}>'是不可分配的类型'AsyncSobject <boolean> - observables和打字稿

// 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并添加“路由保护”,因此路由只能在验证完成后才能激活。

回答

2

这种方法回报和Observable<boolean>不是普通boolean

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

CanActivate实际签名

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

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

+0

感谢花花公子,这解决了它。没有更多的打字稿编译错误。 – TetraDev

相关问题