LogoLogo
v3.7
v3.7
  • README
  • Getting Started
    • Why
    • Installation
  • Concepts
    • Introduction
    • Store
    • Actions
    • State
    • Select
  • Advanced
    • Action Handlers
    • Actions Life Cycle
    • Cancellation
    • Composition
    • Error Handling
    • Ivy Migration Guide
    • Lazy Loading
    • Life-cycle
    • Mapped Sub States
    • Meta Reducers
    • Optimizing Selectors
    • Options
    • Shared State
    • State Token
    • State Operators
    • Sub States
  • Recipes
    • Authentication
    • Caching
    • Component Events from NGXS
    • Debouncing Actions
    • Dynamic Plugins
    • Immutability Helpers
    • Module Federation
    • Style Guide
    • Unit Testing
    • RxAngular Integration
  • Snippets
    • State Operators
  • Plugins
    • Introduction
    • CLI
    • Logger
    • Devtools
    • Storage
    • Forms
    • Web Socket
    • Router
    • HMR
  • NGXS Labs
    • Introduction
  • Community
    • FAQ
    • Resources
    • Contributors
    • Contributing
    • Sponsors
  • Changelog
Powered by GitBook
On this page
  • Basic
  • Advanced
  1. Advanced

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.

import { Injectable } from '@angular/core';
import { State, Action } from '@ngxs/store';

@State<ZooStateModel>({
  defaults: {
    animals: []
  }
})
@Injectable()
export class ZooState {
  constructor(private animalService: AnimalService, private actions$: Actions) {}

  @Action(FeedAnimals, { cancelUncompleted: true })
  get(ctx: StateContext<ZooStateModel>, action: FeedAnimals) {
    return this.animalService.get(action.payload).pipe(
      tap((res) => ctx.setState(res))
    ));
  }
}

Advanced

For more advanced cases, we can use normal Rx operators.

import { Injectable } from '@angular/core';
import { State, Action, Actions, ofAction } from '@ngxs/store';
import { tap } from 'rxjs/operators';

@State<ZooStateModel>({
  defaults: {
    animals: []
  }
})
@Injectable()
export class ZooState {
  constructor(private animalService: AnimalService, private actions$: Actions) {}

  @Action(FeedAnimals)
  get(ctx: StateContext<ZooStateModel>, action: FeedAnimals) {
    return this.animalService.get(action.payload).pipe(
      tap((res) => ctx.setState(res)),
      takeUntil(this.actions$.pipe(ofAction(RemoveTodo)))
    ));
  }
}
PreviousActions Life CycleNextComposition

Last updated 2 years ago