【问题标题】:Ngrx Effects not listening to actionsNgrx Effects 不听动作
【发布时间】:2019-03-14 11:56:25
【问题描述】:

我想在我的 Angular 应用 (v7) 中使用 ngrx/efffects 和 ngrx/store。我按照ngrx documentation 中的建议在我的应用程序中配置了一切。在 AppComponent 中调度操作时,reducer 按预期工作,但看起来 效果没有监听任何操作

测试:

在执行ng serve -o 之后检查控制台。一切都按预期记录,但生效的除外。

请指出我哪里出错了。

Github Repo

效果

@Injectable()
export class AppEffects {
  constructor(
    private actions$: Actions,
    private myService: MyserviceService
  ) {}

  myAction$ = this.actions$.pipe(
    ofType<fromActions.GetItems>(MyActionTypes.GET_ITEMS),
    switchMap(action => {
      console.log('i am in effects', action);
      return this.myService.getItems().pipe(
        map(data => new fromActions.GetItemsSuccess(data)),
        catchError(err => of(new fromActions.GetItemsSuccess(err)))
      );
    })
  );
}

AppModule 中配置的效果

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    StoreModule.forRoot(reducers, { metaReducers }),
    EffectsModule.forRoot([AppEffects])
  ],
})

AppComponent 中的调度操作

export class AppComponent implements OnInit {
  constructor(private store: Store<State>) {
    console.log('in component');
  }

  ngOnInit() {
    console.log('dispatched action in AppComponent');
    this.store.dispatch(new fromAction.GetItems());
  }
}

【问题讨论】:

  • 请在问题中贴出一些相关的代码部分

标签: angular ngrx ngrx-effects


【解决方案1】:

您缺少 @Effect() 装饰器,否则这些可观察对象将不会被注册为商店的副作用。

import { Effect, Actions, ofType } from '@ngrx/effects';

//....

@Injectable()
export class AppEffects {
 //  ....

  @Effect()
  myAction$ = this.actions$.pipe(
    ofType<fromActions.GetItems>(MyActionTypes.GET_ITEMS),
    switchMap(action => {
      console.log('i am in effects', action);
      return this.myService.getItems().pipe(
        map(data => new fromActions.GetItemsSuccess(data)),
        catchError(err => of(new fromActions.GetItemsSuccess(err)))
      );
    })
  );
}

【讨论】:

  • 如果有任何组织角度项目结构的最佳实践,您能否提出建议。?
猜你喜欢
  • 2016-12-22
  • 2017-11-19
  • 2016-12-28
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多