NGXS 使用运算符更新状态,然后将数据持久化到 firebase
NGXS updating state using operators and then persisting data to firebase
我有一个操作类型 class 来更新用户:
export class Update {
public static readonly type = '[Users] Update';
constructor(public readonly id: string, public readonly changes: Partial<User>) {}
}
下面是动作:
@Action(Update)
public update({ getState, setState }: StateContext<UsersStateModel>, { id, changes }: Update) {
setState(
patch({
users: updateItem(u => u.id === id, patch(changes))
})
);
// const userToUpdate = getState().users.find(u => u.id === id);
// return this.userService.update(userToUpdate);
}
但是我不知道如何正确地将这些数据发送到我的 http 服务。我发现的所有其他示例包括先将数据发送到后端,然后才将结果分配给状态。
注释的代码可以完成工作,但感觉不对。有什么建议可以使它正常工作吗?
你是说也许是这样吗?
@Action(Update)
public update({ getState, setState }: StateContext<UsersStateModel>, { id, changes }: Update) {
const currentUser = getState().users.find(u => u.id === id);
const userWithAppliedChanges = { ...currentUser, ...changes };
return this.userService.update(userWithAppliedChanges).pipe(
map(updatedUser => setState(...)),
catchError(() => EMPTY)
);
}
我有一个操作类型 class 来更新用户:
export class Update {
public static readonly type = '[Users] Update';
constructor(public readonly id: string, public readonly changes: Partial<User>) {}
}
下面是动作:
@Action(Update)
public update({ getState, setState }: StateContext<UsersStateModel>, { id, changes }: Update) {
setState(
patch({
users: updateItem(u => u.id === id, patch(changes))
})
);
// const userToUpdate = getState().users.find(u => u.id === id);
// return this.userService.update(userToUpdate);
}
但是我不知道如何正确地将这些数据发送到我的 http 服务。我发现的所有其他示例包括先将数据发送到后端,然后才将结果分配给状态。
注释的代码可以完成工作,但感觉不对。有什么建议可以使它正常工作吗?
你是说也许是这样吗?
@Action(Update)
public update({ getState, setState }: StateContext<UsersStateModel>, { id, changes }: Update) {
const currentUser = getState().users.find(u => u.id === id);
const userWithAppliedChanges = { ...currentUser, ...changes };
return this.userService.update(userWithAppliedChanges).pipe(
map(updatedUser => setState(...)),
catchError(() => EMPTY)
);
}