问题
Below is an action that dispatches a load action to the store. The corresponding effect will handle the request and sends back the response items.
But What I want is I want to toggle the below action with a button.
So if I press start it will start dispatching actions every 1 s and if I press pause, it will pause dispatching and again If I press start it will continue from where it left, and repeats so...
How can I toggle such an action?
let date = 1587513626000; // date is required because the backend only sends data with a start and end date
interval(1000).pipe(tap(_ => {
this.store.dispatch(loadStoreItems({ limit: 10, start: date, end: date + 1000 }))
date += 1000
}))
.subscribe()
I've tried a bunch of operators, some of them are partially working (like sometimes using takeWhile/ takeUntil I'm being able to pause) but not being able to restart.
回答1:
to have a toggle in an effect you need 2 actions (start and stop) and to use takeUntil
.
//effects.ts
loadCourierItems$ = createEffect(() =>
this.actions$.pipe(
ofType(actions.start),
exhaustMap(action => interval(1000).pipe(
// logic for every second activity.
map(actions.everySecondAction()),
)),
takeUntil(this.actions$.pipe(ofType(actions.stop))),
repeat(),
)
)
//app.component.ts
constructor(private store: Store<CourierItemsState>) {
}
ngOnInit() {
this.store.dispatch(startAction());
}
ngOnDestroy() {
this.store.dispatch(stopAction());
}
来源:https://stackoverflow.com/questions/61427341/how-can-i-toggle-start-stop-an-ngrx-action