Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Last active December 22, 2017 22:21
Show Gist options
  • Save amcdnl/eb1f7e9892b161bc9b79a88265bddc78 to your computer and use it in GitHub Desktop.
Save amcdnl/eb1f7e9892b161bc9b79a88265bddc78 to your computer and use it in GitHub Desktop.
export class EatPizza { }
export class CookPizza {
constructor(public payload: Pizza) {}
}
@Component({ ... })
export class MyComponent {
@Select(PizzaStore.pizzas)
cooking: Observable<boolean>;
constructor(private store: Store<PizzaState>) {
store.actions$.pipe(ofType(CookPizza), tap(s => alert('pizza')));
}
click(pizza) {
this.store.dispatch(new CookPizza(pizza)).subscribe((res) => {
alert('Pizza Cooking!');
});
}
click2() {
this.dispatch([ new CookPizza(), new EatPizza() ]);
}
}
@NgModule({
imports: [
Ngxs.forRoot([
{ store: PizzaStore, plugins: [AtomicState] }
])
]
})
export class MyModule {}
@Store<PizzaState>({
pizzas: [],
cooking: false,
emailed: false
})
export class PizzaStore {
static pizzas = (state) => state.pizzas;
static eating = (state) => state.eating;
constructor(private pizzaSvc: PizzaService) {}
@Action(EatPizza)
eatPizza({ state }) {
return { ...state, eating: true };
}
@AsyncAction(CookPizza)
cookPizza({ state, next, complete }, order: Pizza) {
next(state = { ...state, cooking: true });
this.pizzaService.cook(order).subscribe(s => {
next(state = { ...state, cooking: false });
this.pizzaService.emailOrderer(order)
.subscribe(() => {
next({ ...state, emailed: true });
complete();
});
});
}
@AsyncAction(CookPizza)
cookPizza({ state }, order: Pizza) {
return this.pizzaSvc.cook(order).pipe(
map(res => { ...state, ...res }));
}
@AsyncAction(ChainExample)
chainExample({ dispatch, complete }) {
dispatch(new EatPizza()).subscribe(() =>
dispatch(new CookPizza({ peppers: true }).subscribe(() =>
complete()));
}
}
@Store<PizzaState>({
pizzas: [],
cooking: false,
emailed: false
})
export class PizzaStore {
static pizzas = (state) => state.pizzas;
static eating = (state) => state.eating;
constructor(private pizzaSvc: PizzaService) {}
@Mutation(EatPizza)
eatPizza = ({ state }) => { ...state, eating: true };
@Action(CookPizza)
cookPizza = ({ dispatch }, order: Pizza) =>
this.pizzaSvc.cookPizza().subscribe((pizza) => {
dispatch(new EatPizza());
dispatch(new ChainAction(pizza));
});
@Action(ChainAction)
chainAction = ({ dispatch }, order: Pizza) => {
combineAll(
dispatch(new CookPizza(order)),
dispatch(new DelieverPizza())
).pipe(tap(() => dispatch(new EatPizza()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment