'Get the result value from an observable stream

I am using an angular 12 project.

I have an observable:

     export class RegisterUserShellComponent implements OnInit {

       constructor(private store: Store<State>) { }

       user$: Observable<User>;
       isNull$: Observable<Boolean>; 

       ngOnInit(): void {
            this.user$ = this.store.select(getSelectedUser);
       }
      
     }

Here is the User class definition:

    export interface User {
        id: string | null;
        name: String;
        socialMedia: SocialMedia;
        companyName: string;
    }

I need to get the value from user$, check if it is null or not and assign it to isNull$.

My question is how can I read a property from the value user$ stream to process the value (to check if it is null or not) and assign the result to isNull$?



Solution 1:[1]

Assuming that this.store.select(getSelectedUser) returns an observable, you could then subscribe to it, check if a value is returned, and set isNull$ to be an observable using of() with the boolean of that check.

    export class RegisterUserShellComponent implements OnInit {
    
       constructor(private store: Store<State>) { }
    
       user$: Observable<User>;
       isNull$: Observable<Boolean>; 
    
       ngOnInit(): void {
            this.user$ = this.store.select(getSelectedUser);
            this.user$.subscribe(user => this.isNull$ = of(!!user))
       }
    }

Solution 2:[2]

To get the result from an observable within a component just subscribe. I'm not sure why you declared isNull as an observable if you're going to assign a boolean to it, so I'm going to assume that was a mistake.

export class RegisterUserShellComponent implements OnInit {

    constructor(private store: Store<State>) { }

    user$: Observable<User>;
    isNull: boolean; 

    ngOnInit(): void {
         this.user$ = this.store.select(getSelectedUser);
         this.user$.subscribe((user) => (this.isNull = !!user));
    }
      
}

Let me know if I've misunderstood your question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Red2678
Solution 2 Chris Hamilton