Angular Observable定时请求无法获取数据库最新数据求助
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
killTriggerisn’t firing early: Make sure you only callthis.killTrigger.next()inngOnDestroy()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

