Reputation: 1526
Worked with Angular for a while, so while working through a NativeScript tutorial I decided to try out the NGXS data store for the first time. I've tried ~5 different NGXS written tutorials (starting with the NS docs) but can't get state to update despite no errors thrown by Android Studio or NS.
NGXS 3.5 | Angular 8.0 | NativeScript 5.4
final state of attempt => https://github.com/argarner/ns-ng-course/commits/ngxs-failed-integration
// app.module.ts
import { NgxsModule } from '@ngxs/store';
import { ChallengeState } from './shared/challenge.state';
...
imports: [
...
NgxsModule.forRoot([ChallengeState])
],
// ./shared/challenge.state.ts
import { State, Action, StateContext, Selector } from '@ngxs/store';
export class SetChallengeAction {
static readonly type = '[Challenge Edit Component] Set Challenge';
constructor(public payload: string) {}
}
export interface ChallengeStateModel {
currentChallenge: string;
}
@State<ChallengeStateModel>({
name: 'challenge',
defaults: {
currentChallenge: 'kjsdjfkljslkfsd'
}
})
export class ChallengeState {
@Selector()
static getChallenge(state: ChallengeStateModel) {
return state.currentChallenge;
}
@Action(SetChallengeAction)
setChallenge(
{ patchState }: StateContext<ChallengeStateModel>,
{ payload }: SetChallengeAction
) {
patchState({ currentChallenge: payload });
}
}
// current-challenge.component.ts
import { Select, Store } from '@ngxs/store';
import { ChallengeState } from '~/app/shared/challenge.state';
export class CurrentChallengeComponent {
currentChallenge: Observable<string>;
constructor(private store: Store) {
this.currentChallenge = this.store.select(
state => state.challenge.currentChallenge
);
}
}
// current-challenge.component.html
<Label class="title" [text]="currentChallenge | json"></Label>
If I don't use the json pipe the Label text displays as [object object]
With the json pipe the Label text is { "_isScalar": false }
This never changes no matter how I get, set or access NGXS State.
What am I missing? Is there a fundamental incompatibility with NGXS and NS?
Upvotes: 1
Views: 792
Reputation:
Store.prorotype.select
returns an Observable
, thus you have to pipe with an async
pipe first:
<Label class="title" [text]="currentChallenge | async"></Label>
Also you don't need to map the state using the callback, you've already created a memoized selector, everything you have to do is:
currentChallenge = this.store.select(ChallengeState.getChallenge);
Upvotes: 3