【问题标题】:How to save dynamic component to ngrx/store? How to load dynamic component from ngrx/store?如何将动态组件保存到ngrx/store?如何从ngrx/store 加载动态组件?
【发布时间】:2019-06-07 12:22:41
【问题描述】:

我想将动态组件保存到@ngrx/store。但我收到 ERROR TypeError: Cannot freeze when dispatch an action from my component.

我参考了这个页面Why do I get "TypeEror: Cannot freeze"?。我复制了组件对象。但我仍然收到此错误。

组件:

ngOnInit() {
    this.contents$ = this.store.pipe(select(fromContents.getContents));
}

addPhotoChild() {
  const componentFactory = this.CFR.resolveComponentFactory(
    PhotoChildComponent
  );
  const componentRef: ComponentRef<PhotoChildComponent> = 
                   this.VCR.createComponent(componentFactory);
  const currentComponent = componentRef.instance;

  currentComponent.selfRef = currentComponent;
  currentComponent.index = this.index++;
  currentComponent.userId = this.user.id;
  currentComponent.uploadedPhoto.subscribe(val => {
    this.photo = val;
    const cloneComp = Object.assign({}, currentComponent);
    this.store.dispatch(new SaveContents({ comp: cloneComp }));
  });
  currentComponent.compInteraction = this;
  this.componentsReferences.push(componentRef);
}

行动:

export class SaveContents implements Action {
  readonly type = ContentsActionTypes.SAVE_CONTENTS;
  constructor(public payload: { comp: PhotoChildComponent | GmapChildComponent }) {}
}

export class LoadContents implements Action {
  readonly type = ContentsActionTypes.LOAD_CONTENTS;
}

减速机:

export interface ContentsState extends EntityState<PhotoChildComponent | GmapChildComponent> {
  allContentsLoaded: boolean;
}

export const adapter: EntityAdapter<PhotoChildComponent | GmapChildComponent> =
  createEntityAdapter<PhotoChildComponent | GmapChildComponent>();

export const initialContentsState: ContentsState = adapter.getInitialState({
  ids: [],
  entities: {},
  allContentsLoaded: false
});

export function contentsReducer(state = initialContentsState, action: ContentsActions) {
  switch (action.type) {
    case ContentsActionTypes.LOAD_CONTENTS: {
      return {
        ...state,
        allContentsLoaded: true
      };
    }
    case ContentsActionTypes.SAVE_CONTENTS: {
      return adapter.addOne(action.payload.comp, state);
    }

    default:
      return state;
  }
}

选择器:

export const selectContentsState = createFeatureSelector<ContentsState>('contents');

export const getContents = createSelector(
  selectContentsState,
  adapter.getSelectors().selectAll
);

【问题讨论】:

    标签: angular ngrx ngrx-store angular-dynamic-components


    【解决方案1】:

    不要将组件的实例保存在 ngRx 存储中。

    创建一个服务,它将保留您要动态呈现的组件的集合。设置组件名称为key,组件工厂为value。

    在商店中,您可以保留组件的名称,并使用它从您创建的服务中检索组件。

    【讨论】:

      猜你喜欢
      • 2016-12-28
      • 2019-07-24
      • 2017-08-30
      • 1970-01-01
      • 2017-01-12
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多