Angular 8 NativeScript应用程序无法设置或获取NGXS状态

时间:2019-07-24 07:38:17

标签: angular nativescript ngxs

使用Angular已有一段时间,因此在阅读NativeScript教程时,我决定首次尝试NGXS数据存储。我尝试了大约5种不同的NGXS书面教程(从NS文档开始),但是尽管Android Studio或NS没有抛出任何错误,也无法获得状态更新。

NGXS 3.5 |角度8.0 | NativeScript 5.4

最终尝试状态=> 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>

如果我不使用json管道,则标签文本显示为[object object]

使用json管道,标签文本为{ "_isScalar": false }

无论我如何获取,设置或访问NGXS状态,这都不会改变。

我想念什么? NGXS和NS是否存在根本的不兼容性?

1 个答案:

答案 0 :(得分:2)

Store.prorotype.select返回一个Observable,因此您必须先使用async管道进行管道:

<Label class="title" [text]="currentChallenge | async"></Label>

此外,您不需要使用回调映射状态,您已经创建了一个记忆选择器,您要做的就是:

currentChallenge = this.store.select(ChallengeState.getChallenge);