新数据对象的"id"应该在哪里created/assigned?

Where should the "id" of the new data object be created/assigned?

我正在使用 Angular 7 构建 Web 应用程序,并希望使用 @ngrx/store 和 @ngrx/effects.

免责声明:我是这些技术的新手。

在典型的客户端-服务器应用程序中,我认为允许数据库分配 id 值是有意义的,然后该值将在 HTTP 响应中传回给客户端。

但是考虑到 API 调用应该在使用 NGRX 时发生副作用,使用 http 响应中返回的 id 更新状态中的新对象的正确方法是什么?

我的理解是副作用不应该操纵状态。这就是它们被称为副作用的全部原因。

解决这个问题的正确方法是什么?

一些可能性:

  • 您可以让客户端生成自己的 ID。
  • 您只能在服务器往返完成后将实体添加到商店。 这可以通过从服务器返回整个对象来完成,或者在效果中将 id 附加到实体:
@Effect()
  save = this.actions.pipe(
    ofType(Foo),
    exhaustMap(({ payload }) =>
      this.service.post(payload).pipe(
        map(
          result =>
            new FooSuccess({
              ...payload,
              id: result,
            })
        ),
        catchError(() => of(new FooFailed()))
      )
    )
  );
  • 状态操作确实是通过 reducer 完成的,如果你能以某种方式 link 商店中的新实体与返回的有效负载你可以通过 reducer 更新 id
@Effect()
  save = this.actions.pipe(
    ofType(Foo),
    exhaustMap(({ payload }) =>
      this.service.post(payload).pipe(
        map(
          result =>
            new FooSuccess({
              reference: payload.reference,
              id: result,
            })
        ),
        catchError(() => of(new FooFailed()))
      )
    )
  );


// and in the reducer

return {
   ...state, 
   // mutate found entity, else just return the entity in the store
   entities: this.state.entities.map(p => p.reference === action.reference ? mutateEntityHere : p)
}

我的偏好是第一个或第二个选项。