Home > Mobile >  Type 'Observable<true | undefined>' is not assignable to type 'Observable<bo
Type 'Observable<true | undefined>' is not assignable to type 'Observable<bo

Time:09-15

This is a type script file im trying to implement auth guard from an observable from another service but this annoying error keeps popping up

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree, } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { map, Observable } from 'rxjs';
import { AccountsService } from 'src/Services/Accounts.service';

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

  constructor(private accountsService: AccountsService, private toastr: ToastrService, private router: Router) {}


  canActivate(): Observable<boolean> {
  return this.accountsService.currentUser$.pipe(
    map((user) =>{
      if(user) return true;
    })
  )  
}
}

enter image description here

CodePudding user response:

Your map is returning undefined if there is no user.

You need to return a value for every case :

map((user) =>{
  return user !== null && user !== undefined;
})

CodePudding user response:

Well, the problem is that you only return something from the map only when the user is truthy. You should return for the other case as well. Try this:

canActivate(): Observable<boolean> {
  return this.accountsService.currentUser$.pipe(
    map((user) => !!user)
  );
}

CodePudding user response:

if the condition fails, the function returns the default value, i.e. undefined, but your function should return boolean

canActivate(): Observable<boolean> {
 return this.accountsService.currentUser$.pipe(map(Boolean));
}
  • Related