На самом деле, я застрял с проблемой с управлением состоянием ngxs (3.2.0) для моего объекта даты. Я пытаюсь обновить дату отображения в своем приложении (приложение Angular 6 с угловым материалом), действие отправлено правильно, и объект даты изменяется в этом состоянии, но подписчики ничего не делают, когда дата изменилась, и, следовательно, мой шаблон не обновляется.
Вот мой файл действий currentDate.action.ts:
export class CreateDate {
static readonly type = '[app] create date';
constructor(public payload: Date) { }
}
export class ChangeDate {
static readonly type = '[app] change date';
constructor(public payload: Date) { }
}
export class IncrementDate {
static readonly type = '[app] increment date';
constructor() { }
}
export class DecrementDate {
static readonly type = '[app] decrement date';
constructor() { }
}
Вот мой currentDate.state.ts:
export interface CurrentDateModel {
selectedDate: Date;
currentDate: Date;
checker: number;
}
@State<CurrentDateModel>({
name: 'currentDate',
defaults: {
currentDate: new Date(),
selectedDate: new Date(),
checker: 0
},
})
export class CurrentDateState {
@Action(CreateDate)
createDate(ctx: StateContext<CurrentDateModel>, { payload }: CreateDate) {
ctx.patchState({ currentDate: payload });
}
@Action(IncrementChecker)
IncrementChecker(ctx: StateContext<CurrentDateModel>) {
const state = ctx.getState();
state.checker = state.checker + 1;
ctx.setState(state);
}
@Action(IncrementDate)
IncrementDate(ctx: StateContext<CurrentDateModel>) {
const state = ctx.getState();
state.selectedDate.setMonth(state.selectedDate.getMonth() + 1);
ctx.setState(state);
}
@Action(DecrementDate)
DecrementDate(ctx: StateContext<CurrentDateModel>) {
const state = ctx.getState();
state.selectedDate.setMonth(state.selectedDate.getMonth() - 1);
ctx.setState(state);
}
@Action(ChangeDate)
changeDate(ctx: StateContext<CurrentDateModel>, { payload }: ChangeDate) {
ctx.patchState({ currentDate: payload });
}
}
Код в моем файле header.ts:
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
@Select(state => state.currentDate.selectedDate) currentDate: Observable<Date>;
@Select(state => state.currentDate.checker) check: Observable<number>;
constructor(private store: Store) { }
ngOnInit() {
this.currentDate.subscribe((date) => console.log('hello from header', date));
this.check.subscribe(() => console.log('i changed'));
}
increment() {
this.store.dispatch(new IncrementChecker());
}
decrementDate() {
this.store.dispatch(new DecrementDate());
}
incrementDate() {
this.store.dispatch(new IncrementDate());
}
}
В моем файле template.html:
<mat-toolbar color="primary">
<div>
<a mat-button routerLink="">Test</a>
</div>
<div>{{check | async}}</div>
<div><mat-icon (click)="decrementDate()">arrow_left</mat-icon></div>
<div>{{currentDate | async | date:'MMMM' | titlecase}}</div>
<div><mat-icon (click)="incrementDate()">arrow_right</mat-icon></div>
<div fxFlex fxLayout fxLayoutAlign="flex-end">
<button mat-button>Se connecter</button>
</div>
<div><button mat-button (click)="increment()">Increment</button></div>
</mat-toolbar>
Я пробовал много вещей (вот почему вы тоже можете видеть переменную "check" в моих файлах), но мне не удалось увидеть обновление с объектом date, но удалось выполнить другой объект, такой как моя проверка здесь или мои другие объекты состояния .
Если у вас есть идеи или вы видите большую ошибку в моем коде ...