3

On an Angular 11 / Typescript application I have:

authorize(policy: Policy) : Observable<boolean> {

  switch(policy) { 

    case Policy.Admin: 

      return zip(this.authenticationService.isSignedIn(), this.user$).pipe(
        map(([isSignedIn, user]: [boolean, UserModel]) => 
          isSignedIn 
          && 
          user?.claims?.some((claim: Claim) => claim.value === 'Admin'))
      );

user is of type Observable<UserModel> and isSignedIn is of type Observable<boolean, undefined>.

When I build the application I get the error:

Type 'Observable<boolean | undefined>' is not assignable to type 'Observable<boolean>'

I do not want to return undefined. I would prefer to return false instead of undefined.

How can I do this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • I'm pretty sure that `user?` will return undefined if `user` is undefined which may be where the `undefined` is coming from. You could try putting some checks for undefined and returning false in those cases – Hive7 Mar 05 '21 at 19:16

1 Answers1

2

End your map with a boolean ...

  const isSignedIn$ = this.authenticationService.isSignedIn();
  const user$ = this.user$;

  return zip(isSignedIn$, user$).pipe(
    map(([isSignedIn, user]: [boolean, UserModel]) => {
        const hasAdminRole = user?.claims?.some((claim: Claim) => claim.value === 'Admin');
        
        return !!(isSignedIn && hasAdminRole);
    })
  );
Stavm
  • 7,833
  • 5
  • 44
  • 68