angular - 操作 CREATE_SUCCES 后重定向

标签 angular ngrx

我有一个组件来创建新记录...提交表单时,我会发送一个 CREATE 操作。

在这个组件的 OnInit 中我有一个 ActionsSubject 订阅 捕捉 CREATE Action 的完成。完成后我重定向到概览组件。

这在我第一次插入记录时工作正常,但是当尝试添加第二条记录时,一旦我回到创建组件并且我被重定向回概览,就会立即点击 actionssubject 完成订阅。

redirectSub: Subscription;

constructor(
  private store: Store<fromRoot.State>,
  private router: Router,
  private actionsSubject: ActionsSubject
) { }


ngOnInit() {
  this.redirectSub = this.actionsSubject.asObservable().pipe(
    ofType(ContactsActionTypes.CREATE_SUCCESS)
  ).subscribe(
    (action: CreateSuccess) => this.router.navigate(['/contacts', action.payload.id])
  );
}

ngOnDestroy() {
  this.redirectSub.unsubscribe();
}

submitted(subspecialisatie: SubSpecialisatie) {
  this.store.dispatch(new Create(subspecialisatie));
}




@Effect()
create$: Observable<Action> = this.actions$.pipe(
ofType(SubSpecialisatiesActionTypes.CREATE),
map((action: Create) => action.payload),
switchMap((subspecialisatie) => this.subspecialisatieService.createSubSpecialisatie(subspecialisatie)),
map((createdSubSpecialisatie: SubSpecialisatie) => new CreateSuccess(createdSubSpecialisatie))
);

我应该能够回到创建组件而不会立即被重定向...

最佳答案

我想我明白你做错了什么,你正在监听 Action 并在组件处理它,这是不好的。你应该听取 Action 只在reducers(如果它是同步处理程序+它产生新状态)或效果(如果它是异步处理程序,或者只是副事件)。 因此,您可以在Effects 处收听CREATE_SUCCESS在那里重新路由。例如:

constructor(
   ...,
   private router: Router,
   ...
) { }

@Effect({ dispatch: false })
createSuccess$: Observable<Action> = this.actions$.pipe(
   ofType(SubSpecialisatiesActionTypes.CREATE_SUCCESS),
   tap((action) => this.router.navigate(['/contacts', action.payload.id]))
);

希望对您有所帮助。

关于angular - 操作 CREATE_SUCCES 后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476891/

相关文章:

javascript - 如何在Typescript中获取特定 "keyof"参数的类型?

Angular - 与 react 形式的子组件交互

javascript - HttpClient 中的 Angular 变化检测

angular - 何时在 angular2 中使用 ngrx/effect

Angular 2 ngrx : what is the proper way to immutably update an array of objects in reducers?

css - 自动调整 HTML 表格列

angular - FormControl 上的 ValueChanges 在 Form.enable 时触发,即使使用 emitEvent : false

带有 ngrx 的 Angular 2 router v3 observable guard

angular - 在 ngrx 上创建非记忆化选择器

typescript - 使用 TypeScript 2.4.1 在 @ngrx/effects 中观察到的操作出错