繁体   English   中英

错误“属性‘switchmap’在类型‘Observable’上不存在<user | null> " 当保护管理路由时</user>

[英]Error "Property 'switchmap' does not exist on type 'Observable<User | null>" when protecting admin route

我的管理员身份验证服务 ts 在下面

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { AuthService } from './auth.service';
import 'rxjs/Rx';
import { UserService } from './user.service';



@Injectable({
  providedIn: 'root'
})
export class AdminAuthGaurdService implements CanActivate {

  constructor(private auth:AuthService,private userServise:UserService) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.auth.user$
      .switchmap((user: { uid: String; }) => this.userServise.get(user.uid))
      .map((appUser: { isAdmin: any; })=>appUser.isAdmin);
  }
}

错误是“‘Observable<User | null>’.ts(2339) 类型上不存在属性‘switchmap’”。 我不知道如何解决这个问题。 我已经完成了所有事情甚至使用管道。 尽我所能

问题与疑虑

  1. 您需要Observable.pipe()方法来链接多个运算符

  2. 有一个拼写错误,应该是switchMap而不是switchmap运算符的 switchmap。

  3. canActivate方法应该具有Observable<boolean>的返回类型,因为您正在返回具有Observable<boolean>类型的值。

您的代码应如下所示:

import { map, switchMap } from 'rxjs';

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean> {
  return this.auth.user$.pipe(
    switchMap((user: { uid: String }) => this.userServise.get(user.uid)),
    map((appUser: { isAdmin: any }) => appUser.isAdmin)
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM