首页仅首次加载与刷新时调用API的实现方案咨询
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
tapoperator 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
相关产品推荐
相关产品推荐

