代码之家  ›  专栏  ›  技术社区  ›  David Bulté

在ngrx(使用ngrx/effects)中,如何检索新创建项的ID?

  •  4
  • David Bulté  · 技术社区  · 6 年前

    但是,如何在生成CREATE_Book操作的BookComponent中获取新创建图书的ID呢?我只能想到解决办法:

    • 在BookComponent中检索图书的完整列表。最后一本是创作的书。
    • 不要使用ngrx/效果。只需调用BookService.create()方法并订阅它。从那里发送创建图书成功操作。但为什么首先要使用效果呢?
    2 回复  |  直到 6 年前
        1
  •  2
  •   maxime1992    6 年前

    我也遇到过这种情况,我认为你有两个选择:

    • 第一个也是最简单的一个,您可以使用UUID库直接在前端创建ID,但可能您的ID是在后端生成的,您不能这样做

    生成一个ID并在操作的有效负载内传递它(如果需要,还可以在当前的有效负载内传递)。举个例子 actionId .

    从你的效果,当你映射到动作 CREATE_BOOK_SUCCESS 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个不同的订阅,这是完全可以的。

        2
  •  2
  •   timdeschryver    6 年前

    不能直接让组件知道已创建的ID,因为必须遵循redux的单向数据流。

    如果您真的想在某个地方使用ID,您可以将其存储在前面提到的存储状态中,或者创建ID客户端。

    trackBy function *ngFor 指示并在新创建的项上创建动画。

    更多效果用法,请查看 Start using ngrx/effects for this