javascript - การตรวจสอบสิทธิ์ Angular2 - ประเภท 'AsyncSubject<{}>' ไม่สามารถกำหนดค่าให้กับประเภท 'AsyncSubject' - observables และ typescript
ฉันเป็นมือใหม่ในการใช้ observables และ typescript ดังนั้นฉันจึงกำลังทำอะไรบางอย่างผิด นี่คือคอมโพเนนต์การตรวจสอบสิทธิ์ของฉันสำหรับ 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 และเพิ่ม 'การป้องกันเส้นทาง' เพื่อให้เส้นทางสามารถเปิดใช้งานได้เฉพาะหลังจากการยืนยันตัวตนเสร็จสมบูรณ์
คำตอบ #1
วิธีนี้จะคืนค่าเป็น Observable<boolean> ไม่ใช่ boolean ธรรมดา:
canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean> {
ลายเซ็นจริงของ CanActivate คือ
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean>|boolean
ซึ่งหมายความว่าทั้งสองสามารถใช้ได้ แต่โค้ดของคุณจริง ๆ จะคืนค่า Observable<boolean>
