Get the result value from an observable stream

1k Views Asked by At

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$?

3

There are 3 best solutions below

0
wlf On BEST ANSWER

Use rxjs, there is no need to manually subscribe. This solution also keeps isNull$ as an observable.

this.user$ = this.store.select(getSelectedUser);
this.isNull$ = this.user$.pipe(map(user => user === null));

Then (if relevant) use theasync pipe against each observable in your template.

1
Red2678 On

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

2
Chris Hamilton On

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.