Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

Why is there a property `type` on a NGXS Action

I'm reading about NGXS and which, for example, looks like this:

export class NewState {
    static readonly type = '[State] New';
    constructor(public payload: MyState) { }
}

In my store I can listen for that action

@Action(New)
newState(ctx: StateContext<MyState>, { payload }: { payload: MyState }) {
    ctx.setState(payload);
}

So, although I specified a static type as [State] New I don't see it anywhere coming back in my code.

My first thought was, because it is an identifier, it is needed if you have multiple action, like this

@Action(New)
@Action(Add)
newState(ctx: StateContext<MyState>, action: MyState | AddState) {
    if (action.constructor.type === New.type) {
        ctx.setState(payload);
    } else {
        // do something else
    } 
}

But then again, you can do it without type of course like this action.constructor === New and probably even better to just use a separate function fo each one of them :)

So, my question is: When should I use type?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need type. That's how NGXS works. It doesn't check based on an instance.
From the docs:

Each action contains a type field which is their unique identifier.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...