ngrx效果导致错误并且没有正确触发

时间:2018-01-24 23:04:12

标签: angular ngrx ngrx-effects

我目前正在使用ngrx 4.1.1在angular 5.2.1中构建一个ngrx breadcrumb组件。这是一项正在进行中的工作,因此仍有一些部分需要修复。

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

效果" 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);
        });
}

1 个答案:

答案 0 :(得分:2)

问题是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);
});