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

相關問題