我目前正在使用ngrx 4.1.1在angular 5.2.1中构建一个ngrx breadcrumb组件。这是一项正在进行中的工作,所以我仍然需要修复一些部分。
我目前在更改效果中得到一个错误。错误是:
Effect "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);
});
}
发布于 2018-01-24 23:15:40
问题是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);
});
https://stackoverflow.com/questions/48433160
复制相似问题