我有一个包含JSON的状态,如下所示:
{id: "1", name: "ig1", description: "ig 11"}
{id: "5", name: "hhh", description: "hhh"}
{id: "6", name: "ggg", description: "hhh"}
我需要从状态数组中选择id = 1的数据
如何使用NGXS状态选择器完成
我们如何在组件中访问它?
我的状态中有以下内容
食谱
0 : {id: "3", name: "Cake", image: "index.jpg", description: "Lorem Ipsum is
simply dummy text of the printing a…ldus PageMaker including versions of
Lorem Ipsum.", ingredients: "ig 1-1kg,ig 123-4kg"}
1 : {id: "16", name: "gfdg", image: "Chrysanthemum.jpg", description:
"fhfgh",
ingredients: "gdfg-4sfhs,ig 1-1kg"}
2 : {id: "17", name: "hfgh", image: "Jellyfish.jpg", description: "ghgfh",
ingredients: "ig 123-5kg,ig 1-3kg"}
3 :{id: "18", name: "hgj", image: "Koala.jpg", description: "ghjhgj",
ingredients: "gdfg-5sfhs"}
我想获取索引1处于状态的数据,即{id:“ 16”,名称:“ gfdg”,图像:“ Chrysanthemum.jpg”,说明:“ fhfgh”,成分:“ gdfg-4sfhs,ig 1-1kg“}
根据您的回复,我在代码下面添加了
在组件中:
import { RecipeState } from '../../state/recipe.state';
edit_details : Observable<string[]>;
editRecipepopup( id ) {
this.edit_details = this.store.select(RecipeState.findById).pipe(map(filterFn
=> filterFn(id)));
console.log("edit=>",this.edit_details);
}
状态:
@Selector()
static findById(state: string[]) {
return (id: string) => { //<--- Return a function from select
console.log("id=>"+id);
return state.filter(s => s.indexOf(id) > -1);
};
}
但是我没有得到数据。另外,我的ID未登录控制台
答案 0 :(得分:4)
在这里,这是查询状态的方法:
在您的状态文件中:
@Selector()
static getIndexed(state: any[]) {
return (index: number) => { //<--- Return a function from select
return state[index];
};
}
来自您的组件:
this.store.select(YourState.getIndexed).pipe(map(filterFn => filterFn(YOUR_INDEX)));
WORKING DEMO (有关更多详细信息,请参见 Do Read )