【发布时间】:2021-05-02 09:38:09
【问题描述】:
我是 Angular 新手。
我该如何解决这个问题?
我已经安装了 Angular CLI: 11.0.7 和 Node: 12.18.4
我已经安装了一个 Angular 路由保护:
ng g guard auth --skip-tests
错误:
错误:src/app/_guards/auth.guard.ts:15:5 - 错误 TS2322:类型 '可观察
' 不可分配给类型 “可观察”。 输入'布尔| 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!')
})
)
}
}
【问题讨论】:
标签: angular angular-router-guards angular-guards