Cancellation
If you have an async action, you may want to cancel a previous Observable if the action has been dispatched again. This is useful for canceling previous requests like in a typeahead.

Basic

For basic scenarios, we can use the cancelUncompleted action decorator option.
1
import { Injectable } from '@angular/core';
2
import { State, Action } from '@ngxs/store';
3
4
@State<ZooStateModel>({
5
defaults: {
6
animals: []
7
}
8
})
9
@Injectable()
10
export class ZooState {
11
constructor(private animalService: AnimalService, private actions$: Actions) {}
12
13
@Action(FeedAnimals, { cancelUncompleted: true })
14
get(ctx: StateContext<ZooStateModel>, action: FeedAnimals) {
15
return this.animalService.get(action.payload).pipe(
16
tap((res) => ctx.setState(res))
17
));
18
}
19
}
Copied!

Advanced

For more advanced cases, we can use normal Rx operators.
1
import { Injectable } from '@angular/core';
2
import { State, Action, Actions, ofAction } from '@ngxs/store';
3
import { tap } from 'rxjs/operators';
4
5
@State<ZooStateModel>({
6
defaults: {
7
animals: []
8
}
9
})
10
@Injectable()
11
export class ZooState {
12
constructor(private animalService: AnimalService, private actions$: Actions) {}
13
14
@Action(FeedAnimals)
15
get(ctx: StateContext<ZooStateModel>, action: FeedAnimals) {
16
return this.animalService.get(action.payload).pipe(
17
tap((res) => ctx.setState(res)),
18
takeUntil(this.actions$.pipe(ofAction(RemoveTodo)))
19
));
20
}
21
}
Copied!
Last modified 1yr ago
Copy link