Home > Software design >  Error "Property 'switchmap' does not exist on type 'Observable<User | null>
Error "Property 'switchmap' does not exist on type 'Observable<User | null>

Time:12-22

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

CodePudding user response:

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