ngrx 效果导致错误且未正确触发

ngrx effect causing an error and not firing properly

我目前正在使用 ngrx 4.1.1 在 angular 5.2.1 中构建一个 ngrx 面包屑组件。这是一个正在进行的工作,所以我还有一些部分需要修复。

我目前在更改效果中遇到错误。错误是:

效果"BreadcrumbEffects.breadcrumbs$"抛出错误 来源:BreadcrumbEffects

错误:TypeError:您在需要流的位置提供了 'undefined'。您可以提供 Observable、Promise、Array 或 Iterable。

只是因为通过 "withLatestFrom" 语句添加了现有状态,我才收到错误。在此之前,我没有 withLatestFrom 语句,我有一个 switchMap 语句而不是 map 语句,它工作正常。我做错了什么?

我的效果声明如下

/* Effects handle the actual execution of the action */
import { Injectable } from "@angular/core";
import { BreadcrumbService } from "./breadcrumb.service";
import { Observable } from "rxjs/Observable";
import * as moment from "moment";
import { Action, Store } from "@ngrx/store";
import { Effect, Actions } from "@ngrx/effects";
import { BreadcrumbActionTypes, ChangeBreadcrumbsAction, ChangeBreadcrumbsCompleteAction } from "./breadcrumb.actions";
import * as fromBreadcrumbReducer from "./breadcrumb.reducers";

@Injectable()
export class BreadcrumbEffects {

    crumbs$: Observable<any>;

    constructor(private readonly actions$: Actions,
        private readonly store$: Store<fromBreadcrumbReducer.BreadcrumbState>,
        private readonly breadcrumbService: BreadcrumbService) {

        this.crumbs$ = this.store$.select(fromBreadcrumbReducer.Selectors.getBreadcrumbs);
    }

    @Effect()
    breadcrumbs$: Observable<ChangeBreadcrumbsCompleteAction> =
    this.actions$
        .ofType(BreadcrumbActionTypes.ChangeBreadcrumbs)
        .withLatestFrom(this.crumbs$)
        .map((result: any) => {
            let action: ChangeBreadcrumbsAction, crumbs: any[];
            [action, crumbs] = result;
            /* make a copy of the existing crumbs. */
            /* this code is still being worked on, hence the hardcoded index */
            const newCrumbs = crumbs.slice(0);
            if (crumbs.length > 0) {
                newCrumbs[1] = { ...newCrumbs[1], displayName: action.name }
            }
            return new ChangeBreadcrumbsCompleteAction(newCrumbs);
        });
}

问题是 this.crumbs$ 被传递给了 withLatestFrom(this.crumbs$),但它只有在构造函数中赋值后才会被定义。

您可以使用 defer:

解决问题
import { defer } from "rxjs/observable/defer";
...
.withLatestFrom(defer(() => this.crumbs$))

或者通过使用函数声明效果:

@Effect()
breadcrumbs$(): Observable<ChangeBreadcrumbsCompleteAction> {
  return this.actions$
    .ofType(BreadcrumbActionTypes.ChangeBreadcrumbs)
    .withLatestFrom(this.crumbs$)
    .map((result: any) => {
      let action: ChangeBreadcrumbsAction, crumbs: any[];
      [action, crumbs] = result;
      /* make a copy of the existing crumbs. */
      /* this code is still being worked on, hence the hardcoded index */
      const newCrumbs = crumbs.slice(0);
      if (crumbs.length > 0) {
        newCrumbs[1] = { ...newCrumbs[1], displayName: action.name }
      }
      return new ChangeBreadcrumbsCompleteAction(newCrumbs);
});