[英]In ngrx (with ngrx/effects), how to retrieve the ID of a newly created item?
假设您通过从BookComponent调度CREATE_BOOK操作来创建新Book。 在效果中,我们正在处理http保存,之后我们通过CREATE_BOOK_SUCCESS操作将创建的Book传递给reducer。 到现在为止还挺好。
但是如何获得产生CREATE_BOOK操作的BookComponent中新创建的Book的ID? 我只能想到解决方法:
您不能直接让组件知道已创建的ID,因为您必须遵循redux的单向数据流。
如果你真的想在某个地方使用ID,你可以像你提到的那样将它存储在你的商店状态中,或者创建ID客户端。
如果要在列表中的某处突出显示已创建的书籍,可以实现*ngFor
指令的trackBy
函数 ,并在新创建的项目上创建动画。
要获得更多效果,请查看开始使用ngrx / effects
我也一直面临着这种情况,你认为我有两种选择:
生成ID并在操作的有效负载内传递它(如果需要,还可以添加当前的有效负载)。 您可以将其称为例如actionId
。
从您的效果,当您映射到动作CREATE_BOOK_SUCCESS
,也传递您有权访问的ID! (因为我们在处理CREATE_BOOK
操作的代码片段中)。
从(智能)组件中,您可以订阅操作,就像在效果中一样! 所以你可以这样做:
class MyComponent {
// ...
createBook(book: Book) {
// first, generate a unique ID to track the action
// you can call directly the uuid function or even better create
// a uuidService that you inject but for simplicity here I'm not doing it
const actionId: string = uuid();
// then watch for an action of type CREATE_BOOK_SUCCESS with that ID
this.actions.pipe(
ofType<BooksActions.CreateBookSuccess>(BooksActions.CREATE_BOOK_SUCCESS),
filter(({payload}) => payload.actionId === actionId),
first(),
tap(({payload}) => {
// do what you want here
// you've got access to the payload of the CREATE_BOOK_SUCCESS action where
// you have the book returned from the backend (I think)
})
);
// finally, dispatch the action
// it's important to do it after you've subscribed to actions otherwise it might happen
// too fast and you wouldn't get the notification
this.actions.dispatch(new BooksActions.CreateBook({ ...book, actionId }));
}
// ...
}
请注意,我在订阅动作时first
使用这里,所以即使你快速添加10本书,你也会有10种不同的订阅,这是完全没问题的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.