首页 > 解决方案 > 在“缓存”时挂起可观察的阻塞路由器

问题描述

我试图在请求时使用我的服务ngrx/effect来加载数据,但缓存请求以提高效率。我已经阅读了一些示例,它们使用这种方法来存储可观察对象并在存在时再次将其返回,并在publishReplay refCount不发送请求的情况下重做请求的响应。

这一切似乎都很完美——但是在第一次请求之后,如果我重用缓存的 observable,Angular路由器就会停止工作。再次从阅读中,归结为等待可观察的承诺完成?

如何设置服务的消耗以正确解决?

我有一个帮助服务从我的 API 中获取数据,我正在尝试缓存这样的响应:

  getResource(params) {
    if (!this.cache[cacheKey]) {
      this.cache[cacheKey] = this.api.get(RESOURCE_URL, params)
        .pipe(
          publishReplay(1),
          refCount(),
        );
    }
    return this.cache[cacheKey];
  }

(api 服务上的 get 方法看起来像这样)

  get(resource, params?: object): Observable<ApiResponse> {
    return this.http.get<ApiResponse>(resource, params);
  }

效果是这样的:

  @Effect()
  search$: Observable<Action> = this.actions.pipe(
    ofType<Search>(Types.SEARCH),
    debounceTime(300),
    withLatestFrom(this.store.select(state => state.search_properties)),
    distinctUntilChanged(),
    switchMap(([payload, store]) => {

      this.store.dispatch(new GlobalActions.SearchStarted());

      const params = merge({include: ['latestPrint']}, store);

      return this.lookupService
        .getResource(params)
        .pipe(
          map((response: ApiResponse) => {
            this.store.dispatch(new GlobalActions.SearchComplete());
            return new ResultActions.SetSearchResults(response);
          }),
          catchError(() => of(new GlobalActions.EffectError()))
        );
    })
  );

标签: angularrxjsobservablengrx

解决方案


推荐阅读