I use project angular 12.
I have some observable value:
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 the User class defenition:
export interface User {
id: string | null;
name: String;
socialMedia: SocialMedia;
companyName: string;
}
I need to get the id value of the user$ and to 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$?
CodePudding user response:
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.
CodePudding user response:
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))
}
}
CodePudding user response:
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.