首页 > 解决方案 > 使用 Ngrx Effects 生命周期钩子 OnInitEffects (似乎无限发射)

问题描述

我正在尝试了解 Ngrx 7 中引入的效果生命周期挂钩,但我并没有真正理解正在发生的事情。我有一个 Angular 应用程序,并且在效果类中有以下内容,但是, init$ observable 正在无限地发出值。我原以为它会触发一次并完成。我对 observables 也有些陌生。该文档并没有真正帮助我,因为没有太多示例。我可以添加一个 take(1),但我想了解它为什么会一直持续发射。

@Injectable()
export class AuthEffects implements OnInitEffects{

  constructor(private actions$: Actions) {}

  @Effect({dispatch: false})
  login$ = this.actions$.pipe(
    ofType<LoginAction>(AuthActionTypes.LoginAction),
    tap(console.log)
  );

  @Effect({dispatch: false})
  logout$ = this.actions$.pipe(
    ofType<LogoutAction>(AuthActionTypes.LogoutAction),
    tap(console.log)
  );

  @Effect()
  init$ = this.actions$.pipe(
    ofType<Action>('[Auth] Effects Init'),
    tap(console.log)
  );

  ngrxOnInitEffects(): Action {
    console.log('AuthEffects init\'d');
    return { type: '[Auth] Effects Init'};
  }
}

标签: ngrxeffects

解决方案


这是预期的行为 - 效果的主要用途是作用于某些第三方副作用。并且您设置它在任何动作ofType<Action>发生时发出,而例如:

  @Effect({dispatch: false})
  login$ = this.actions$.pipe(
    ofType<LoginAction>(AuthActionTypes.LoginAction),
    tap(console.log)
  );

每当LoginAction发生时发出。


推荐阅读