首页 > 解决方案 > 为什么使用该服务缓存http请求时api会被调用2次

问题描述

当页面第一次加载或手动重新加载页面时,api 被调用 2 次,这两个 get 请求。之后,当您转到其他组件并通过路由器链接返回家中时,不会再次调用 api,因此它可以工作,但唯一的问题是在刷新时,api 被调用 2 次而不是 1 次。

数据服务

 import { Injectable } from '@angular/core';
 import { HttpClient, HttpBackend } from '@angular/common/http';
 import { environment } from '../../environments/environment';
 import { Observable, of } from 'rxjs';

    public responseCache = new Map();

      constructor(private http: HttpClient, private handler: HttpBackend) {
        this.http = new HttpClient(this.handler);
       }

      getTimeZone(): Observable<any> {
        const URL = environment.BACKEND_HOST + 'api/timezone';
        const fromCache = this.responseCache.get(URL);
        if (fromCache) {
          return of(fromCache);
        }
        const response = this.http.get<any>(URL);
        response.subscribe(res => this.responseCache.set(URL, res));
        return response;
      }

Home 组件 我如何称呼它

this.data.getTimeZone().subscribe((data: any)=> {
        this.timezones = data;
      })

标签: angular

解决方案


subscribe一次response进入getTimeZone并返回response,然后subscribe再次使用this.data.getTimeZone().subscribe(...). 这就是它被调用两次的原因。

您可以使用map()或可tap()管道操作符getTimeZone而不是订阅它:

getTimeZone(): Observable<any> {
    const URL = environment.BACKEND_HOST + 'api/timezone';
    const fromCache = this.responseCache.get(URL);
    if (fromCache) {
      return of(fromCache);
    }
    const response = this.http.get<any>(URL);
    return response.pipe(
          tap(res => {
               this.responseCache.set(URL, res)
           })
         );

  }

做/点击:https ://www.learnrxjs.io/operators/utility/do.html


推荐阅读