当使用 Angular 路由守卫时: 'Observable<true | undefined>' 不可分配给类型 > 'Observable<boolean>'

Jah*_*han 3 angular angular-router-guards angular-guards

我是角度新手。

我怎么解决这个问题?

我已经安装了 AngularCLI: 11.0.7和 Node:12.18.4

我已经安装了 Angular 路线防护:

ng g guard auth --skip-tests
Run Code Online (Sandbox Code Playgroud)

错误:

错误: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 => {
             ~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

警卫

代码:

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!')
      })
    )
  }
  
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*l D 6

可能是因为未定义map时运算符不会返回任何内容。user尝试返回一些东西

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;
        this.toastr.error('You shall not pass!');
        return false;
      })
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

或者更好的是,您可以使用tap运算符而不是map执行“toastr”通知等副作用。

export class AuthGuard implements CanActivate {
  constructor(private accountService: AccountService, private toastr: ToastrService) {}

  canActivate(): Observable<boolean> {
    return this.accountService.currentUser$.pipe(
      tap(user => {
        if (!user) this.toastr.error('You shall not pass!')
      })
    )
  }
}
Run Code Online (Sandbox Code Playgroud)