I'm dispatching saved Settings from an API. A Setting has an 'ID' and a couple objects like 'numberOfUsers' etc. Furthermore I'm using NGXS for state management.
I only want to get the 'numberOfUsers' and use it in my template. But for some reason my subscription is for a millisecond undefined and than has the data (see image). I also tried to map, but I really don't know what's the best practise here and how to get the data in my template.
Here is my code:
@Select(SettingsState.getSettings)
settings$!: Observable<Settings[]>;
settingsChanged!: Settings[];
ngOnInit(): void {
this.store.dispatch(new GetSettings(this.settingsId));
this.settings$.subscribe((data: Settings[]) => {
console.log('data', data);
return this.settingsChanged = data;
}
);
}
console.log('settingsChanged', this.settingsChanged);
Try this it may help!
Filter : is used to filter null responses.
map: is used to get only the properties that you want.
import { filter, map } from 'rxjs/operators';
this.settings$.pipe(map((data) => {
if(data) {
return {
id: data.ID,
attempts: data.numberOfUsers,
key: data.others,
}
}}),
filter(res => res && res != undefined)
).subscribe((data: any) => {
console.log('data', data);
alert(data.id);
return this.settingsChanged = data;
}
);
Working Example : link
Good luck.