Reputation: 176
I'm getting data from ngrx store in component. In the map function, I process the data and prepare it for display in the component. The final result is stored in the object. The component implements filters by query parameters. I subscribe to the activated route to get the current query parameters and then to filter my data. When I'm trying to access proccessed object I recieve empty object instead. How do I get the processed result from ngrx store in subscription to query parameters?
events$: Observable<Event[]>;
eventsByDay = {}; // empty object for proccessed data
ngOnInit(): void {
this.events$ = this.store.pipe(
select(EventQuery.getAllEvents),
filter((events) => events.length > 0),
map((events: Event[]) => {
// some logic to proccess data from store
this.eventsByDay = { //proccessed data };
return events;
});
this.activatedRoute.queryParams.subscribe((queryParams) => {
console.log(this.eventsByDay); --> empty
});
}
Upvotes: 0
Views: 1422
Reputation: 373
You can use combineLatest to wait until both observables emit something:
import { combineLatest } from 'rxjs'
...
ngOnInit(): void {
this.events$ = this.store.pipe(
select(EventQuery.getAllEvents),
filter((events) => events.length > 0),
map((events: Event[]) => {
// some logic to proccess data from store
this.eventsByDay = { //proccessed data };
return events;
});
// don't forget to unsubscribe!
combineLatest([this.activatedRoute.queryParams, this.events$])
.subscribe(([query, events]) => {
console.log(events, query);
console.log(this.eventsByDay); // will be the same as events
});
}
Upvotes: 1