Kir*_*ran 5 observable rxjs5 ngrx angular
我有一个需要在Angular应用程序中对两个@Ngrx操作进行排序的场景。
第一个动作使用一些数据更新状态,第二个动作使用该数据触发服务器调用。我正在使用效果对这两个动作进行排序,并仅在第一个动作完成后才触发第二个动作。
为了确保第二个动作包括来自状态的最近更新的数据,我将存储注入到我的效果中,并使用选择器函数检索数据并将其作为第二个动作的有效负载包括在内。
这可行。
我的问题
但是,我相信,由于this.actions$已经是可观察的流,因此我应该能够简单地转换该流上的每个事件并将其转换为不同的动作。
我所想到的粗略的大理石图:

我正在使用withLatestFrom运算符将操作流与状态数据组合在一起。
@Effect()
lazyEffect1$ = this.actions$.ofType(LazyActions.TEST_ACTION_SEQUENCE)
.withLatestFrom(this.filterId$, (x, y) => {
return new LazyActionDone(y.number);
});
Run Code Online (Sandbox Code Playgroud)
但是这段代码给了我一个错误:
TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
我已经能够使用稍微不同的结构来使其工作,下面的代码中也包含该结构。
但我想了解为什么lazyEffect1不能正常工作。我的理解力在哪里使我失望?
代码
NgRx还原剂:
// reducers.ts
export function lazyReducer(
state: any = {},
action: LazyAction | LazyActionDone
) {
switch (action.type) {
case LazyActions.TEST_ACTION_SEQUENCE: {
console.info('Action Received in Reducer: ', action.type);
return {
...state,
number: action.payload
};
}
case LazyActions.TEST_ACTION_SEQUENCE_DONE: {
console.info('Done Received in Reducer: ', action.type);
return {
...state,
retrieved: action.payload,
done: true
};
}
default: {
return state;
}
}
}
Run Code Online (Sandbox Code Playgroud)
NgRx效果:
// effects.ts
@Injectable()
export class LazyEffects {
private filterId$: Observable<any>;
constructor(
private actions$: Actions,
private store: Store<any>
) {
this.filterId$ = this.store.select(getLazyState);
}
// THIS DOES NOT WORK
@Effect()
lazyEffect1$ = this.actions$.ofType(LazyActions.TEST_ACTION_SEQUENCE)
.withLatestFrom(this.filterId$, (x, y) => {
// console.info(x, y);
return new LazyActionDone(y.number);
});
// THIS WORKS
@Effect()
lazyEffect2$ = this.actions$.ofType(LazyActions.TEST_ACTION_SEQUENCE)
.switchMap((action) => {
console.info('Action Received in Effects: ', action.type);
return of(action).withLatestFrom(this.filterId$, (x, y) => new LazyActionDone(y.number));
});
}
Run Code Online (Sandbox Code Playgroud)
只是为了阐明@cartant 提供的解决方案..我相信解决方案是替换此属性:
// THIS DOES NOT WORK
@Effect()
lazyEffect1$ = this.actions$.ofType(LazyActions.TEST_ACTION_SEQUENCE)
.withLatestFrom(this.filterId$, (x, y) => {
// console.info(x, y);
return new LazyActionDone(y.number);
});
Run Code Online (Sandbox Code Playgroud)
有了这个功能:
@Effect()
lazyEffect1$() {
return this.actions$.ofType(LazyActions.TEST_ACTION_SEQUENCE)
.withLatestFrom(this.filterId$, (x, y) => {
// console.info(x, y);
return new LazyActionDone(y.number);
});
}
Run Code Online (Sandbox Code Playgroud)
@cartant在评论中的回答值得赞扬,但我想为遇到此问题但没有注意到答案在评论中的其他人提供答案/示例。
| 归档时间: |
|
| 查看次数: |
779 次 |
| 最近记录: |