import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http'; // Optional, for type consistency
export interface FetchOptions {
primaryUrl: string;
fallbackUrl?: string; // Alternative CORS-friendly URL (e.g., proxy or JSONPlaceholder)
fallbackData?: any; // Static mock data as final fallback
timeoutMs?: number; // Optional timeout
}
/**
* Angular service using native Fetch API to fetch data from a primary source.
* Automatically handles CORS and network errors by falling back to secondary sources.
*
* Usage example in a component:
* ```
* constructor(private dataService: DataService) {}
*
* async ngOnInit() {
* try {
* const data = await this.dataService.fetchWithFallback({
* primaryUrl: 'https://api.example.com/data', // May have CORS issues
* fallbackUrl: 'https://jsonplaceholder.typicode.com/users', // CORS-enabled fallback
* fallbackData: [{ id: 1, name: 'Fallback User' }] // Final static fallback
* });
* console.log(data);
* } catch (error) {
* console.error('All fallbacks failed:', error);
* }
* }
* ```
*/
@Injectable({
providedIn: 'root'
})
export class DataService {
/**
* Fetches data with fallback logic for CORS/network errors.
* Tries primary URL -> fallback URL -> static fallback data.
* @param options Configuration for fetch attempts
* @returns Promise resolving to parsed JSON data
*/
async fetchWithFallback(options: FetchOptions): Promise<any> {
const { primaryUrl, fallbackUrl, fallbackData, timeoutMs = 10000 } = options;
// Helper function to fetch with timeout
const fetchWithTimeout = async (url: string): Promise<Response> => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, {
signal: controller.signal,
headers: {
'Accept': 'application/json',
},
});
clearTimeout(timeoutId);
return response;
} catch (error: any) {
clearTimeout(timeoutId);
throw error;
}
};
// Try primary URL
try {
console.log(`Fetching from primary: ${primaryUrl}`);
const response = await fetchWithTimeout(primaryUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error: any) {
console.warn(`Primary fetch failed (${primaryUrl}):`, error.message);
// Common CORS error indicators: "Failed to fetch", "TypeError: Failed to execute 'fetch'"
const isCorsOrNetworkError = error.name === 'TypeError' || error.message.includes('fetch') || error.message.includes('CORS');
if (!isCorsOrNetworkError) {
throw error; // Re-throw non-recoverable errors
}
}
// Try fallback URL if provided
if (fallbackUrl) {
try {
console.log(`Falling back to secondary URL: ${fallbackUrl}`);
const response = await fetchWithTimeout(fallbackUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error: any) {
console.warn(`Fallback URL failed (${fallbackUrl}):`, error.message);
}
}
// Use static fallback data if provided
if (fallbackData !== undefined) {
console.log('Using static fallback data');
return fallbackData;
}
// All fallbacks exhausted
throw new Error('All data sources failed. No fallback available.');
}
}
Key Features:
- CORS/Network Error Handling: Catches
TypeError or messages indicating fetch/CORS failures and seamlessly falls back.
- Multi-Level Fallbacks:
- Primary URL (e.g., external API with potential CORS issues).
- Fallback URL (e.g., CORS-enabled public API like JSONPlaceholder).
- Static mock data (e.g., hardcoded array/object).
- Timeout Support: Prevents hanging requests (default 10s).
- Logging: Console logs for debugging each step.
- Generic & Reusable: Pass options for any endpoint.
- No External Dependencies: Pure Fetch API + Angular Injectable.
- Error Propagation: Throws on final failure or non-CORS errors (e.g., 5xx).
Integration Notes:
- Development Proxy: For local dev, configure
proxy.conf.json in Angular to bypass CORS for primary URLs.
- Production: Use a backend proxy (e.g., NGINX) or CORS-enabled services for primary fetches.
- Testing: Mock
fetch globally in unit tests or use MSW for API mocking.
This service is production-ready and handles real-world CORS pitfalls gracefully!