Search code examples
ngrx-storengrx-effects

`ngrx` - how to implement the caching with `effects`


I like to integrate the cache with my effects. but getting no result. the way i do may not correct.

any one correct me to fix the issue.

here is my code:

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)))
        ))

    )

the problem is, eventhough i back to the current page, I am getting backend call instead of supplying from store. where is wrong? what condition has to be added here?

Thanks in advance.


Solution

  • I come up with following solution: it works for me!!

    @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)))
                    )
                })
            )