【问题标题】:Ngrx Effects withLatestFrom causes an exceptionNgrx Effects withLatestFrom 导致异常
【发布时间】:2019-07-22 01:24:48
【问题描述】:

我正在尝试发送一个操作,该操作将根据所选出版商加载书籍。

下面是效果类的示例:

@Injectable()
export class LibraryEffects {
    @Effect({})
    bookRequest = this.actions.pipe(
        ofType(BOOK_LIST_REQUEST),
        withLatestFrom(
            this.store.pipe(
                select(selectBookshop),
                map(bookshop => bookshop.library.publisher),
            )
        ),
        map(([action, publisher]) => {
            window.console.log(action, publisher);
            return new BookRequestSuccess();
        })
    );

    constructor(
        private actions: Actions,
        private store: Store<AppState>
    ) {}
}

当应用程序启动时,存储既不包含“书店”也不包含“图书馆”属性,这些属性稍后会被用户操作填充。之后,用户触发“BOOK_LIST_REQUEST”操作并应检索适当的图书列表。

但是即使没有调用应该订阅存储中的“库”属性的“BOOK_LIST_REQUEST”操作,只要注册了效果就会发生异常:

core.js:15714 ERROR TypeError: Cannot read property 'library' of null

这似乎很奇怪,好像 effect 是在模块中注册一个 observable 到存储中,而不是在调用 'BOOK_LIST_REQUEST' 操作时。

这里可能有什么问题?我在这种效果下从存储中读取数据是否有问题?

【问题讨论】:

  • 看起来AppState 没有使用默认状态初始化。请分享您的AppState 以及reducer 和selector 代码。
  • 它被初始化为默认状态。简单的默认状态不包含这些属性。问题在于订阅那些在注册效果而不是动作调度时发生的属性。
  • 然后确保从reducer默认返回初始状态switch case

标签: angular ngrx ngrx-effects


【解决方案1】:

如果 withLatestFrom 像在 ngrx documentation example (collection.effects.ts) 中那样被包裹在 concatMap 运算符中,这个问题似乎得到了解决。

        ofType(BOOK_LIST_REQUEST),
        concatMap(action => of(action).pipe(
          withLatestFrom(this.store.pipe(
            select(selectBookshop), 
            map(bookshop => bookshop.library.publisher)
         )
       )

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多