[英]Angular2 + ngrx/store: how to change state within a loop?
在使用ngrx / store的Angular2应用程序中,我有一种方法可以从API查询一些数据并将其分派到商店。 一切正常:
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;
});
}
我还有另一个服务,查询API ans返回数组os对象。 在这种情况下,我正在这样做:
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;
})
它可以工作,但是存储的状态会多次更改。 有没有更好的方法? 也许还要创建另一个动作(“ GET_CONTENTS”),以便同时存储商店中的所有商品? 还是我可以说,状态只能在“ contents.map”结束后才能更改?
一个简单的解决方案是编辑您的reducer以使用Array<Content>
有效负载。 然后,在单个Content
的情况下,只需将该值分派到数组中即可:
this.store.dispatch({ type: 'GET_CONTENT', [content] });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.