如果效果返回缓存结果,则 Angualr componen't 不会挂载



我正在尝试缓存http请求以减少流量,在任务效果中,我检查是否已经检索到用户任务。但当我这样做时,当我返回缓存的任务时,组件不会渲染。如果您删除它并再次发出http请求,它将继续工作。

这是任务效果类

@Injectable()
export class TasksEffect {
@Effect() fetchEffects = this.actions$.pipe(
ofType(TaskListActions.FETCH_TASKS),
withLatestFrom(this.store.select('tasksModule')),
switchMap(([action, tasksModule]) => {
if (tasksModule.tasks.length) {
return of(new TaskListActions.SetTasks([...tasksModule.tasks]));
}
return this.taskService.fetchTasks((action as TaskListActions.FetchTasks).interval)
.pipe(
catchError(err => of(err)),
switchMap(tasks => of(new TaskListActions.SetTasks(tasks))),
);
})
);
constructor(private taskService: TaskService, private store: Store<fromTasks.AppState>, private actions$: Actions) {
}
}

我的代码有问题吗?如果是这样,我该怎么修?还有没有更好的方法来缓存http请求,比如在react 中存储memory

在您的代码中,catchError(err => of(err))应该在switchMap之后,因为在发生错误的情况下,错误将减少为TaskListActions.SetTasks

试着这样做,如果不起作用,请在评论中告诉我。然后你需要检查其他地方,效果很简单,也许this.taskService.fetchTasks有问题。

@Injectable()
export class TasksEffect {
@Effect() fetchEffects = this.actions$.pipe(
ofType(TaskListActions.FETCH_TASKS),
withLatestFrom(this.store.select('tasksModule')),
switchMap(([action, tasksModule]) => {
if (tasksModule.tasks && tasksModule.tasks.length) {
return of(new TaskListActions.SetTasks([...tasksModule.tasks]));
}
return this.taskService.fetchTasks((action as TaskListActions.FetchTasks).interval)
.pipe(
map(tasks => new TaskListActions.SetTasks(tasks)),
catchError(err => of(err)),
);
})
);
constructor(private taskService: TaskService, private store: Store<fromTasks.AppState>, private actions$: Actions) {
}
}

相关内容

最新更新