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

Angular Observable定时请求无法获取数据库最新数据求助

Fixing Angular Observable Not Fetching Fresh Database Data

Hey Abdullah, let's break down why your repeated requests keep returning stale data even after you manually update the database. Here are the most likely culprits and fixes:

1. Your Data Observable Is Being Cached

The biggest issue here is probably how you’re using fetchDataOrderTrackingMapDriverData$. If this is a pre-created Observable (like a direct http.get() assigned to a class property), it only runs once when first subscribed to. Every subsequent trigger from your timer (via switchMap) will just reuse that initial result instead of making a new API call.

Fix: Turn It Into a Reusable Function

Change your data-fetching logic into a method that returns a brand-new Observable every time it’s called:

// Replace your static Observable with this function
private fetchDataOrderTrackingMapDriverData(): Observable<any> {
  return this.http.get<YourDataType>('your-api-endpoint-url', {
    // Add headers to block browser caching
    headers: new HttpHeaders({
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache',
      'Expires': '0'
    })
  });
}

Then update your refresh interval to call this function instead of referencing the static Observable:

private refreshInterval$: Observable<any> = timer(0, 2000)
  .pipe(
    takeUntil(this.killTrigger),
    switchMap(() => this.fetchDataOrderTrackingMapDriverData()), // Call the function here
    catchError(error => {
      console.error('Failed to fetch driver data:', error);
      return of({ status: [] }); // Fallback to prevent subscription breaks
    })
  );

2. Browser or Server Caching Might Be Interfering

Even with new requests, browsers or your backend might be caching the API response. The headers added above tell the browser to skip caching entirely. For the server side, double-check that your API isn’t setting long cache TTLs on responses.

3. Quick Sanity Checks

  • Confirm your killTrigger isn’t firing early: Make sure you only call this.killTrigger.next() in ngOnDestroy() to stop the timer when the component is destroyed.
  • Test your API directly: Use Postman or curl to hit your endpoint after updating the database. If it returns old data, the problem is on the backend, not Angular.

With these changes, your timer will trigger a fresh API request every 2 seconds, pulling the latest database data each time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:16:38