簡體   English   中英

如何從 MatDialog => Rxjs Effect => Component 傳遞數據?

[英]How do I pass data from MatDialog => Rxjs Effect => Component?

我的組件正在調用一個動作並使用@Effect 打開對話框。 對話框將數據發送回@Effect。 我可以在@Effects 中使用.afterClosed() 查看數據,但我不知道如何使用.afterClosed() 將其傳遞給組件。

以下是組件調用對話框的方式:

this.store.dispatch(new fromWorkspace.ShowDialog());

這是效果中的對話框:

  @Effect({ dispatch: false })
   showDialog$ = this.actions$.pipe(
    ofType(WorkspaceActionTypes.ShowDialog),
    map(action => {
      this.dialogRef = this.addPersonDialog.open(PersonSelectorComponent, {
        disableClose: false,
        hasBackdrop: true,
        restoreFocus: true,
        data: { }
      });
      // I can see the data here;
      this.dialogRef.afterClosed().subscribe(result => console.log(result));
    })
  );

以下是 Dialog 如何發回數據:

constructor(@Inject(MAT_DIALOG_DATA) public data: any,
              public dialogRef: MatDialogRef<PersonSelectorComponent>) { }


 addPerson(event: MatAutocompleteSelectedEvent) {
    if (event.option.selected) {
      const person = event.option.value;
      if (person) {
      this.dialogRef.close(person);
      // data is correct here;
      console.log(person);
      }
    }

回到組件這里是我嘗試使用的方式。afterClose():

public dialogRef: MatDialogRef<PersonSelectorComponent>


//this does not work
this.assigneeDialogRef.afterClosed().subscribe(result => console.log(result));

通常,從效果出發,您將使用結果數據發送一個操作,該操作將通過您的減速器 go ,然后最終進入您的數據存儲。 從那里您的組件將被訂閱到數據存儲(通過選擇器)並以這種方式獲取更新的數據。

如果您使用效果直接獲取數據並將其返回到您的組件而不將其放入存儲中,那么我根本不會使用效果。 我只是直接調用對話框並獲得結果並用它做我想做的事。

因此,繼續使用 action/reducer 方法,我執行以下操作:

  • 創建了一個新的操作“addPerson/addPersonSuccess”(以避免訂閱從 Dialog 返回的數據。
  addPerson$ = this.actions$.pipe(
    ofType(WorkspaceActionTypes.AddPerson),
    map(action => {
      return new AddPersonSuccess(action.payload);
    }),
    catchError(error => this.dispatchErrorHandleActions(new addPersonFailure(error),
            `Couldn't add person. Please try again later.`))
  );
  • 然后在reducer中處理它:
 case WorkspaceActionTypes.AddPersonSuccess:

      return update(state, {
        person: {
          data: { $set: action.payload }
        }
      });
  • 並在減速器中包含了一個選擇器:
export const addPerson = createSelector(getWorkspaceState, (state: WorkspaceState) => state.person);
  • 然后回到組件中,在構造函數中調用它:
 this.person$ = this.store.select(fromWorkspace.addPerson);
  • 現在我可以通過訂閱 'this.person$' observable 來獲取數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM