Store
服务。在组件/服务中注入 Store
的方式如下所示:import { Component } from '@angular/core';
import { Store } from '@ngxs/store';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(private store: Store) {}
//...
}
import { State, Action, StateContext } from '@ngxs/store';
export class Increment {
static readonly type = '[Counter] Increment';
}
export class Decrement {
static readonly type = '[Counter] Decrement';
}
// 定义状态模型
export interface CounterStateModel {
count: number;
}
@State({
name: 'counter',
defaults: {
count: 0
}
})
export class CounterState {
// 注册 action
@Action(Increment)
increment(ctx: StateContext) {
const state = ctx.getState();
ctx.patchState({
count: state.count + 1
});
}
@Action(Decrement)
decrement(ctx: StateContext) {
const state = ctx.getState();
ctx.patchState({
count: state.count - 1
});
}
}
select
方法以获取状态的当前值。例如,下面的组件示例演示了如何在 Angular 模板中显示状态:import { Component, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
interface CounterStateModel {
count: number;
}
@Component({
selector: 'app-counter',
template: `
Current count: {{ count$ | async }}
`
})
export class CounterComponent implements OnInit