我在Angular 5项目中使用ngrx / store。 我存储的应用程序状态具有多个属性(切片)。 我希望能够单独听取对任何这些属性的更改。 因此,在这种情况下,我应该使用多个reducer-每个状态切片一个吗? 一个减速器可以实现吗? 我猜它无法完成,因为使用一个化简器,我们将返回整个状态的新副本,而不是切片。 例如
class AppState{
private customerList: Customer [];
private selectedCustomer: Customer;
private countriesOperational: Country [];
}
我希望只能在selectedCustomer上收听更改,所以我可以这样做:
store.select(state => state.selectedCustomer).subscribe((data) => {
})
答案 0 :(得分:1)
首先-不需要多个减速器。一旦您感觉到当前的减速器太大/具有多个可重构性/由于某些限制而应拆分,则应实施新的减速器。
回到您的问题上-假设您的客户具有“ id”属性。在我要演示的场景中,该应用程序将显示当前id的列表-来自customerList。客户清单将使用ngrx动作进行动态更新(模板将监听更改)。
在组件中:
axios.get('/user')
.then((result) => {
res.status(200).json(result.data);
})
.catch((err) => {
if (err.response.status === 401 && err.response.data.errorList.code === "AUTH0007") {
//utill function to get jwt token and update the token in code
// at this point can I send request back with updated token or do I need to ask user to trigger the new req
}
})
在您的模板中:
public customerIds$: Observable<string[]>;
public ngOnInit(): void {
this customerIds$ = this.store.select(
state => state.customersList.map(customer => customer.id);
);
}
现在(使用异步管道),您将html模板与ts组件连接了。因此,假设您有一个将新客户添加到customersList的按钮:
<div *ngFor="let id of customerIds$ | async">
{{id}}
</div>
<button (click)="addNewCustomer()">Add new customer</button>
方法正在调度一个动作,该动作由您的商店处理。动作的结果是在reducer中隐藏,诸如此类:
addNewCustomer()
位置:
action.payload-是您要添加的新客户
[... state.customersList ......]语法-需要使用不可变方法来更新数组-可以在这里找到更多信息:https://vincent.billey.me/pure-javascript-immutable-array/
点击按钮后,新的客户ID将显示在模板中