【问题标题】:Type 'Observable<true | undefined>' is not assignable to type 'Observable<boolean>'输入'可观察的<true | undefined>' 不可分配给类型 'Observable<boolean>'
【发布时间】:2021-08-17 06:49:37
【问题描述】:

我正在尝试为用户创建一个授权系统。我正在使用 Angular11。我在 Angular 方面绝对是新人。我在我的代码中还返回一个布尔类型。但是,我还是发现了一个错误。

下面是我的代码:-

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);
  }
}


我的错误是:-

为什么错误我不明白。我如何解决这个问题。请帮忙。

【问题讨论】:

    标签: angular typescript asp.net-core rxjs angular-observable


    【解决方案1】:

    错误表明 canActivate 方法返回的不是 Observable 而是 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);
          })
    

    您可以通过确保始终返回这样的布尔值来解决此问题

    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;
          })  
    

    【讨论】:

    • 嘿马丁,我很惊讶。因为。看起来你的代码和我发布的代码看起来一样。但是当我复制粘贴你的代码时它可以工作,但我发布的代码不起作用。你实际上在哪里改变。如果你能澄清这一点,我很高兴。
    • 当然,地图管道内部存在细微差别。我,v 用地图源代码中的注释更新了我的答案。
    【解决方案2】:

    你需要返回 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);
              })
            )
          }
    

    【讨论】:

    • 我正在使用 Angular11
    猜你喜欢
    • 2020-01-06
    • 2023-01-18
    • 2021-04-18
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多