I am calling a NGXS Action with the store.dispatch() function within a subscribtion. I need the data from the subscribed observable before i call the store.dispatch() function and therefore i somehow have to wait for the observable to deliver the data. I dont know how i can fix this code so the loop will be prevented. Does someone of you know how to handle this correctly?
@Select(NepoState.anlagen) myObserveable$: Observable<Anlage[]>;
ngOnInit(): void {
this.myObserveable$.subscribe((data) => {
this.store.dispatch(new ChangeAvalableFilterAction(data); // <-- this causes the loop
})
}
Your dispatch from within the subscribe
is changing the state and firing the selector again. This will dispatch another action and there you have a loop.
You can do following:
ngOnInit(): void {
this.myObserveable$
.pipe(
take(1) // either take just one emission, or using first()
//filter(data => /* or filter according to some condition */)
)
.subscribe((data) => {
this.store.dispatch(new ChangeAvalableFilterAction(data);
})
}