如何在Angular中调用动态API获取实时数据?
Hey there! Let's walk through how you can access that real-time API data and integrate it with your existing Angular setup. Here's a step-by-step breakdown tailored to your code:
First, open the Google Drive file you linked to get critical info about the real-time API:
- The actual API endpoint URL (not the Drive file link itself—this will be the URL you send requests to)
- Authentication requirements: Does it need an API key, OAuth token, or specific request headers?
- Response structure: Confirm if the data format matches the DraftKings API you're currently using (this will save you time adjusting parsing logic later)
Real-time data typically uses either HTTP polling (regularly fetching fresh data) or WebSockets (persistent connection for instant updates). Below are examples for both approaches, built on your existing code:
Option 1: HTTP Polling (Simplest for Most APIs)
This refreshes data at a set interval (e.g., every 30 seconds) to mimic real-time updates. Update your api.component.ts like this:
import {Component, OnDestroy} from '@angular/core'; import {HttpClient} from '@angular/common/http' import {forkJoin, interval, Subscription} from 'rxjs'; import {map, switchMap} from 'rxjs/operators'; @Component({ selector: 'app-mlb-api', templateUrl: './mlb-api.component.html', styleUrls: ['./mlb-api.component.css'] }) export class MlbApiComponent implements OnDestroy { all: Array<{line: string, name: string,oddsAmerican:string}> = []; private refreshSubscription: Subscription; // Adjust interval time (ms) based on how frequently you need updates private refreshInterval = 30000; constructor(private http: HttpClient) {} ngOnInit() { // Initial data load this.fetchRealTimeData().subscribe(); // Start polling for updates this.refreshSubscription = interval(this.refreshInterval) .pipe(switchMap(() => this.fetchRealTimeData())) .subscribe(); } private fetchRealTimeData() { // Replace with the real-time API endpoint from your document const realTimeApiUrl = 'YOUR_REAL_TIME_API_ENDPOINT'; // Add any required auth headers/params (e.g., API key) const httpOptions = { headers: { 'Authorization': 'Bearer YOUR_API_KEY', // Remove if no auth is needed 'Content-Type': 'application/json' } }; // Fetch real-time data (adjust the map logic to match the API's response structure) const realTimeData$ = this.http.get(realTimeApiUrl, httpOptions) .pipe(map((resp: any) => resp.events)); const fantasyLabsData$ = this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17'); return forkJoin([realTimeData$, fantasyLabsData$]).pipe( map(([realTimeResp, fantasylabsResp]) => { this.allName = realTimeResp.map(r => r.name); this.allline = realTimeResp.map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line); this.allline = this.allline.filter(l => !!l); this.allOdds = realTimeResp.map(r => r.offers).flat().map(r=>r.outcomes[0]).flat().map(o=>o.oddsAmerican); this.createAllArray(); }) ); } createAllArray(): void { this.all = []; // Clear old data to avoid duplicates for (let i = 0; i < this.allline.length; i++) { this.all.push({ line: this.allline[i], name: this.allName[i], oddsAmerican: this.allOdds[i] }); } } ngOnDestroy() { // Clean up the subscription to prevent memory leaks this.refreshSubscription?.unsubscribe(); } }
Option 2: WebSockets (For Instant Updates)
If the real-time API uses WebSockets (look for wss:// in the endpoint), use Angular's WebSocketSubject for a persistent connection:
import {Component, OnDestroy} from '@angular/core'; import {HttpClient} from '@angular/common/http' import {forkJoin, WebSocketSubject, Subscription} from 'rxjs'; import {map} from 'rxjs/operators'; @Component({ selector: 'app-mlb-api', templateUrl: './mlb-api.component.html', styleUrls: ['./mlb-api.component.css'] }) export class MlbApiComponent implements OnDestroy { all: Array<{line: string, name: string,oddsAmerican:string}> = []; private socketSubscription: Subscription; private socket$: WebSocketSubject<any>; constructor(private http: HttpClient) {} ngOnInit() { // Initialize WebSocket connection (replace with your endpoint) this.socket$ = new WebSocketSubject('wss://YOUR_REAL_TIME_WEBSOCKET_ENDPOINT'); // Subscribe to incoming real-time messages this.socketSubscription = this.socket$.subscribe( (message) => this.processRealTimeData(message), (error) => console.error('WebSocket error:', error), () => console.log('WebSocket connection closed') ); // Load initial fantasy labs data this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17').subscribe(); } private processRealTimeData(data: any) { // Parse the incoming WebSocket message (adjust based on API's data structure) this.allName = data.events.map(r => r.name); this.allline = data.events.map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line); this.allline = this.allline.filter(l => !!l); this.allOdds = data.events.map(r => r.offers).flat().map(r=>r.outcomes[0]).flat().map(o=>o.oddsAmerican); this.createAllArray(); } createAllArray(): void { this.all = []; for (let i = 0; i < this.allline.length; i++) { this.all.push({ line: this.allline[i], name: this.allName[i], oddsAmerican: this.allOdds[i] }); } } ngOnDestroy() { // Clean up WebSocket connection this.socketSubscription?.unsubscribe(); this.socket$.complete(); } }
- Double-check that the real-time API's response structure matches your parsing logic (use browser dev tools to inspect the API response)
- Add error handling in subscriptions to catch issues like invalid auth or network errors
- Test the interval/connection to ensure updates are working as expected
内容的提问来源于stack exchange,提问作者Karan

