简体   繁体   中英

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

My admin auth serive ts is below

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

The error is "Property 'switchmap' does not exist on type 'Observable<User | null>'.ts(2339)." I can not figure out hoe to crect this. Ihave done every thing even use pipe. and didthe all the impot that I possibley can

Issues & Concerns

  1. You need the .pipe() method of Observable to chain the multiple operators .

  2. There is a typo error, should be switchMap but not switchmap for rxjs operator.

  3. The canActivate method should be with the return type of Observable<boolean> as you are returning the value with the Observable<boolean> type.

Your code should be as below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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