简体   繁体   English

Angular2 + ngrx / store:如何在循环中更改状态?

[英]Angular2 + ngrx/store: how to change state within a loop?

In an Angular2 app using ngrx/store, I have a method that query some data from an API and dispatch it to the store. 在使用ngrx / store的Angular2应用程序中,我有一种方法可以从API查询一些数据并将其分派到商店。 It's working ok: 一切正常:

get(id: number) {
  return this.http.get(`http://localhost:3000/contents/${id}.json`).map( response => {
    return response.json();
  })
  .map( (content: Content) => {
    this.store.dispatch({ type: 'GET_CONTENT', payload: content });
    return content;
  });
}

I have also another service that queries the API ans return an array os objects. 我还有另一个服务,查询API ans返回数组os对象。 In this case, I'm doing this: 在这种情况下,我正在这样做:

return this.http.get(`http://localhost:3000/contents/${id}/contents.json`).map( response => {
  return response.json();
})
.map( ( contents: Array<Content>) => {
  contents.map( payload => {
    this.store.dispatch({ type: 'GET_CONTENT', payload });
  });
  return contents;
})

it works, but the state of the store changes multiple times. 它可以工作,但是存储的状态会多次更改。 Is there a better approach? 有没有更好的方法? Maybe create another action ('GET_CONTENTS') that everything in the store at the same time? 也许还要创建另一个动作(“ GET_CONTENTS”),以便同时存储商店中的所有商品? Or can I say, somehow, that the state should only be changed after the 'contents.map' ends? 还是我可以说,状态只能在“ contents.map”结束后才能更改?

A simple solution would be to edit your reducer to expect an Array<Content> payload. 一个简单的解决方案是编辑您的reducer以使用Array<Content>有效负载。 Then, in the case of a single Content just dispatch that value in an array: 然后,在单个Content的情况下,只需将该值分派到数组中即可:

this.store.dispatch({ type: 'GET_CONTENT', [content] });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM