You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首页仅首次加载与刷新时调用API的实现方案咨询

Solution: Cache API Response to Avoid Re-fetching on Navigation

Step 1: Modify the Service to Cache Data

Use a singleton service to store the fetched data once, so subsequent component initializations don’t trigger new API calls. Add a cached property and check it before making the API request:

// Example service file (e.g., user.service.ts)
private loggedOnTimeCache: string | null = null;

getUserLoggedOn(ipn: string): Observable<{ code: string }> {
  // Return cached data if it exists
  if (this.loggedOnTimeCache) {
    return of({ code: this.loggedOnTimeCache });
  }

  // Fetch from API and cache the response
  return this.http.get<{ code: string }>(`/api/user/logged-on/${ipn}`).pipe(
    tap(response => {
      this.loggedOnTimeCache = response.code;
    })
  );
}

Step 2: Fix Async Race Condition in Component

Your current code calls getLoggedOnTime before this.userIpn is resolved from the async IpnValue() method. Move the API call inside the then block to ensure you pass a valid IPN:

// home.component.ts
ngOnInit() {
  this.Service.IpnValue().then(ipn => {
    this.userIpn = ipn;
    this.getLoggedOnTime(this.userIpn);
  });
}

getLoggedOnTime(ipn: string): void {
  this.Service.getUserLoggedOn(ipn).subscribe(
    (response) => {
      this.lastLoggedOnTime = response.code;
      console.log('User logged on:', this.lastLoggedOnTime);
    },
    (error) => {
      console.error('Error logging on user:', error);
    }
  );
}

Step 3: Optional: Reset Cache When Needed

If you need to clear the cache (e.g., after user logout), add a method to the service:

// user.service.ts
resetLoggedOnTimeCache(): void {
  this.loggedOnTimeCache = null;
}

Key Details

  • Angular services are singletons by default, so the cached value persists across route navigations.
  • The tap operator caches the response without altering the observable stream.
  • Fixing the async flow ensures you never pass an undefined IPN to the API.

内容的提问来源于stack exchange,提问作者web_in

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:01:07