ngrx-如何使用effects实现缓存

时间:2019-05-08 07:30:26

标签: ngrx-store ngrx-effects

我喜欢将缓存与我的效果集成在一起。但没有结果。我的方式可能不正确。

任何人都可以纠正我的问题。

这是我的代码:

constructor(private courseService:CourseService, private actions:Actions,
    private store:Store<StateSetupConfig>){}

@Effect()
    EffLoadCourse = this.actions.pipe(
        ofType(LoadCourse.TYPE),
        withLatestFrom(this.store.pipe(select(subscribes.getCourses)),
            (action, courses) => {
                console.log('courses ::', courses)//getting logged,
                return courses
            }

        ),
       //but each time backend call initiated!!?
        mergeMap((action:LoadCourse) => this.courseService.getCourse().pipe(
            map((courses:ModelCourse[]) => (new LoadCourseSuccess(courses))),
            catchError(err => of(new LoadCourseFail(err)))
        ))

    )

问题是,尽管我回到了当前页面,但我正在接到后端电话,而不是从商店供应商品。哪里错了?在这里必须添加什么条件?

谢谢。

1 个答案:

答案 0 :(得分:0)

我想出以下解决方案:它对我有用!!

@Effect()
        EffLoadCourse = this.actions.pipe(
            ofType(LoadCourse.TYPE),
            withLatestFrom(
                this.store.pipe(select(subscribes.getCourses)), //getting it from store
                (action:LoadCourse, courses: ModelCourse[]) => courses
            ),
            mergeMap((courses:ModelCourse[]) => {

                if(courses.length){
                    return of(courses).pipe(
                        map((courses:ModelCourse[]) => (new LoadCourseSuccess(courses))),
                        catchError(err => of(new LoadCourseFail(err)))
                    )
                }

                return this.courseService.getCourse().pipe(
                    map((courses:ModelCourse[]) => (new LoadCourseSuccess(courses))),
                    catchError(err => of(new LoadCourseFail(err)))
                )
            })
        )