类型 'Observable<true | undefined>' 不可分配给类型 'Observable<boolean>'

Type 'Observable<true | undefined>' is not assignable to type 'Observable<boolean>'

我正在尝试为 users.I 创建一个授权系统,我正在使用 Angular11.I 在 angular.I 中绝对是新的 return 在我的代码中也是一个布尔类型。但是,我还是发现了一个错误。

下面是我的代码:-

auth.guard.ts
(这里是主要问题)

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, 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;
        this.toastr.error(error);
      })
    )
  }
  
}


account.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { ReplaySubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../_models/user';

@Injectable({
  providedIn: 'root'
})
export class AccountService {

  baseUrl='https://localhost:5001/api/';
  private currentUserSource =new ReplaySubject<User> (1);
  currentUser$=this.currentUserSource.asObservable();

  

  constructor(private http :HttpClient) { }

  login(model:any)
  {
    return this.http.post<User>(this.baseUrl+'account/login',model).pipe(

      map((response:User)=>{

        const user=response;
        if(user){
          localStorage.setItem('user',JSON.stringify(user));
          this.currentUserSource.next(user);
        }
      })
    )
  }

  register(model:any)
  {
    return this.http.post<User>(this.baseUrl +'account/register',model).pipe(
      map((user:User)=>{
        if(user){
          localStorage.setItem('user',JSON.stringify(user));
          this.currentUserSource.next(user);
        }
        return user;
        
      })
    )
    
  }



  setCurrentUser(user:User)
  {
    this.currentUserSource.next(user);
  }





  logout()
  {
    localStorage.removeItem('user');  
    
    this.currentUserSource.next(null as any);
  }
}


我的错误是:-

为什么错误我没看懂。我如何解决这个问题。请帮忙

您需要 return observable 而不仅仅是布尔值:

import { of, Observable } from 'rxjs';
    
canActivate(): Observable<boolean> {
        return this.accountService.currentUser$.pipe(
          map(user => {
            if(user) { 
               return of(true);
               }
            this.toastr.error(error);
          })
        )
      }

如果您使用的是 rxjs6,则将以上内容修改为:

import { of as observableOf, Observable } from 'rxjs';
    
canActivate(): Observable<boolean> {
        return this.accountService.currentUser$.pipe(
          map(user => {
            if(user) { 
               return observableOf(true);
               }
            this.toastr.error(error);
          })
        )
      }

错误表明 canActivate 方法不是 returnObservable 而是 Obserable

所以让我们检查一下您的地图管道以了解为什么会这样:

map(user => {
        // we only return here so
        // only true is possible to be returned
        if(user) return true;
        // after this line nothing will be returned so the observable can only return true | undefinded
        this.toastr.error(error);
      })

您可以通过确保始终return像这样的布尔值

来解决这个问题
map(user => {
        if(user) return true;
        this.toastr.error(error);
        // this line bellow is new it changes the return type from true | undefined into boolean
        return false;
      })