Ngrx Component-store :更新商店中的特定字段

时间:2020-12-25 16:30:30

标签: angular typescript ngrx ngrx-store

我在 NGRX 的组件存储库中寻找更新我的模型的单个字段。

这里是商店

export interface MyModelState {
  model: MyModel;
}

@Injectable({
  providedIn: 'root'
})
export class MyModelStoreService extends ComponentStore<MyModelState> {

  constructor() {
// the initial state could contain an empty model
    super({ model: null });
  }

  readonly model$: Observable<MyModel> = this.select(state => state.model);
  readonly updateModel = this.updater( (state, newModel: MyModel) => ({ ...state, model: newModel }) );
}

以及更新模型中值的组件函数:

  updateModel(key, value) {
    this.MyModelStoreService.patchState((state) => { ...state, model: { ...state, key: value } });
  }

查看

    <div *ngIf="myModel$ | async as myModel">

        <div *ngIf="myModel.constructor.name==='First'">
            <input type="number" [(ngModel)]="myModel.value" (ngModelChange)="updateModel('key', $event)" /><br />
        </div>
        <div *ngIf="myModel.constructor.name==='Second'">
            <!-- same for other models type -->
        </div>
    </div>

我知道这个例子不能工作(updateModel 方法),但我可以用正确的方式做到这一点?

0 个答案:

没有答案
相关问题