我是 Angular 的新手。
我怎么解决这个问题?
我已经安装了 AngularCLI: 11.0.7
和 Node:12.18.4
我已经安装了一个 Angular 路由保护:
ng g guard auth --skip-tests
错误:
错误:src/app/_guards/auth.guard.ts:15:5 - 错误 TS2322:类型 'Observable<true | undefined>' 不可分配给类型 'Observable'。输入'布尔| undefined' 不能分配给类型 'boolean'。类型“未定义”不可分配给类型“布尔”。
15 return this.accountService.currentUser$.pipe( ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 16 map(user => { ~~~~~~~~~~~~~~~~~~~ ... 19 }) ~~~~~~~~ 20 ) ~~~~~ src/app/_guards/auth.guard.ts:16:11 - error TS7030: Not all code paths return a value. 16 map(user => { ~~~~~~~~~
代码:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AccountService } from '../_services/account.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private accountService: AccountService, private toastr: ToastrService) {}
canActivate(): Observable<boolean> {
return this.accountService.currentUser$.pipe(
map(user => {
if (user) return true; // the problem occurs here!
this.toastr.error('You shall not pass!')
})
)
}
}