Angular 4中按指定间隔调用带参API报错,求排查问题
Hey there! Let's figure out what's going wrong with your Angular 4 session update code and fix it up step by step.
Core Issues in Your Code
Let's break down the main problems causing the error and missed API calls:
update_User_Session()doesn't return an Observable: TheswitchMap()operator expects you to return an Observable from its callback, but your current method isvoid(no return value). This is the direct cause of your error on that line.- API requests aren't actually firing: Your
INSERT_USER_SESSIONandEND_USER_SESSIONmethods callhttp.get()but don't return the Observable, nor do you subscribe to it. Without this, the HTTP requests never leave the client. - Unintegrated async operations: You're using
publicIp.v4()(a Promise) but aren't properly bridging it with RxJS Observables, which is Angular's preferred way to handle async flows.
Fixed Service Code
First, let's update your service to properly handle Observables and async operations:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { from, forkJoin } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class CartdataService { // Assume these values are defined/updated elsewhere in your service date_and_time: string; session_Begin_Status: string; session_End_Status: string; constructor(private http: HttpClient, private publicIp: /* Your public IP service */) {} update_User_Session() { // Convert the Promise from publicIp.v4() to an Observable return from(this.publicIp.v4()).pipe( map(ip => { // Trigger both API calls and combine their results const endSession$ = this.END_USER_SESSION(ip); const insertSession$ = this.INSERT_USER_SESSION(ip); return forkJoin([endSession$, insertSession$]); }) ); } INSERT_USER_SESSION(address: string) { // Return the HTTP Observable so it can be subscribed to return this.http.get(`http://localhost:xyz/api/data/INSERT_USER_SESSION/?IP_Address=${address}&Time=${this.date_and_time}&state=${this.session_Begin_Status}`); } END_USER_SESSION(address: string) { // Return the HTTP Observable so it can be subscribed to return this.http.get(`http://localhost:xyz/api/data/INSERT_END_USER_SESSION/?Ip_Address=${address}&Time=${this.date_and_time}&state=${this.session_End_Status}`); } }
Fixed Component Code
Now adjust your component to correctly handle the Observable stream, plus add cleanup to avoid memory leaks:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { interval } from 'rxjs'; import { switchMap, mergeMap } from 'rxjs/operators'; import { CartdataService } from './path-to-your-cartdata-service'; @Component({ // Your component's metadata (selector, template, etc.) }) export class YourComponent implements OnInit, OnDestroy { private sessionUpdateSubscription: any; constructor(private CartdataService: CartdataService) {} ngOnInit() { // 15 minutes = 900,000 milliseconds (you had 90,000 which is 1.5 minutes!) this.sessionUpdateSubscription = interval(900000) .pipe( switchMap(() => this.CartdataService.update_User_Session()), // Flatten the combined results from forkJoin mergeMap(results => results) ) .subscribe( response => console.log('API call succeeded:', response), error => console.error('Error updating session:', error) ); } ngOnDestroy() { // Always unsubscribe when the component is destroyed to prevent memory leaks if (this.sessionUpdateSubscription) { this.sessionUpdateSubscription.unsubscribe(); } } }
Key Fixes Explained
- Return Observables consistently: Every method that makes an HTTP call now returns the Observable, allowing RxJS operators to handle the async flow.
- Promise to Observable conversion: Using
from()turns the Promise frompublicIp.v4()into an Observable, aligning it with Angular's RxJS workflow. - Combine API calls with
forkJoin: This ensures both session API calls execute, and we get results from both once they complete. - Fixed interval duration: Adjusted from 90,000ms (1.5 mins) to 900,000ms (15 mins) to match your requirement.
- Component cleanup: Added
ngOnDestroyto unsubscribe from the interval, preventing memory leaks when the component is removed from the DOM.
内容的提问来源于stack exchange,提问作者Nikson
相关产品推荐
相关产品推荐

