Core HTTP services for making requests with XMLHttpRequest and JSONP backends. All methods return RxJS Observables for asynchronous handling with full error support.
Main HTTP service using XMLHttpRequest backend for standard HTTP operations.
/**
* Main HTTP service using XMLHttpRequest backend
* Injectable service for making HTTP requests
*/
class Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions);
/**
* Generic request method supporting all HTTP operations
* @param url - URL string or Request object
* @param options - Optional request configuration
* @returns Observable of Response
*/
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response>;
/**
* GET request method
* @param url - Target URL
* @param options - Optional request configuration
* @returns Observable of Response
*/
get(url: string, options?: RequestOptionsArgs): Observable<Response>;
/**
* POST request method
* @param url - Target URL
* @param body - Request body data
* @param options - Optional request configuration
* @returns Observable of Response
*/
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
/**
* PUT request method
* @param url - Target URL
* @param body - Request body data
* @param options - Optional request configuration
* @returns Observable of Response
*/
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
/**
* DELETE request method
* @param url - Target URL
* @param options - Optional request configuration
* @returns Observable of Response
*/
delete(url: string, options?: RequestOptionsArgs): Observable<Response>;
/**
* PATCH request method
* @param url - Target URL
* @param body - Request body data
* @param options - Optional request configuration
* @returns Observable of Response
*/
patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
/**
* HEAD request method
* @param url - Target URL
* @param options - Optional request configuration
* @returns Observable of Response
*/
head(url: string, options?: RequestOptionsArgs): Observable<Response>;
/**
* OPTIONS request method
* @param url - Target URL
* @param options - Optional request configuration
* @returns Observable of Response
*/
options(url: string, options?: RequestOptionsArgs): Observable<Response>;
}Usage Examples:
import { Http, Headers, RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class UserService {
constructor(private http: Http) {}
// GET request
getUsers(): Observable<any[]> {
return this.http.get('/api/users')
.pipe(
map(response => response.json()),
catchError(error => {
console.error('Error fetching users:', error);
throw error;
})
);
}
// POST with JSON body
createUser(user: any): Observable<any> {
const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers });
return this.http.post('/api/users', JSON.stringify(user), options)
.pipe(map(response => response.json()));
}
// PUT request
updateUser(id: string, user: any): Observable<any> {
const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers });
return this.http.put(`/api/users/${id}`, JSON.stringify(user), options)
.pipe(map(response => response.json()));
}
// DELETE request
deleteUser(id: string): Observable<void> {
return this.http.delete(`/api/users/${id}`)
.pipe(map(response => response.json()));
}
// Custom headers and authentication
getSecureData(): Observable<any> {
const headers = new Headers({
'Authorization': 'Bearer ' + this.getToken(),
'Content-Type': 'application/json'
});
const options = new RequestOptions({ headers });
return this.http.get('/api/secure', options)
.pipe(map(response => response.json()));
}
private getToken(): string {
return localStorage.getItem('authToken') || '';
}
}JSONP HTTP service for cross-domain requests using script injection technique.
/**
* JSONP HTTP service extending Http
* Uses script injection for cross-domain requests
* ⚠️ Security Warning: Vulnerable to XSS attacks
*/
class Jsonp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions);
/**
* JSONP request method - only GET requests allowed
* @param url - Target URL with callback parameter
* @param options - Optional request configuration
* @returns Observable of Response
* @throws Error if non-GET method is used
*/
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response>;
}Usage Examples:
import { Jsonp } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class JsonpService {
constructor(private jsonp: Jsonp) {}
// JSONP request for cross-domain API
getExternalData(): Observable<any> {
const url = 'https://api.external.com/data?callback=JSONP_CALLBACK';
return this.jsonp.get(url)
.pipe(map(response => response.json()));
}
// JSONP with query parameters
searchExternal(query: string): Observable<any> {
const url = `https://api.external.com/search?q=${encodeURIComponent(query)}&callback=JSONP_CALLBACK`;
return this.jsonp.get(url)
.pipe(map(response => response.json()));
}
}import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';
@NgModule({
imports: [
HttpModule, // For Http service
JsonpModule // For Jsonp service
],
// ... other module configuration
})
export class AppModule {}import { NgModule } from '@angular/core';
import { Http, XHRBackend, RequestOptions, BrowserXhr, ResponseOptions, XSRFStrategy } from '@angular/http';
// Custom HTTP factory
export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
return new Http(xhrBackend, requestOptions);
}
@NgModule({
providers: [
{
provide: Http,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions]
}
]
})
export class CustomHttpModule {}import { Http } from '@angular/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError, retry } from 'rxjs/operators';
class ApiService {
constructor(private http: Http) {}
getData(): Observable<any> {
return this.http.get('/api/data')
.pipe(
map(response => {
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
}
return response.json();
}),
retry(3), // Retry failed requests 3 times
catchError(this.handleError)
);
}
private handleError(error: any): Observable<never> {
console.error('HTTP Error:', error);
return throwError(error);
}
}import { Http } from '@angular/http';
import { Observable } from 'rxjs';
import { map, filter, mergeMap } from 'rxjs/operators';
class DataService {
constructor(private http: Http) {}
// Chain multiple HTTP requests
getUserWithPosts(userId: string): Observable<any> {
return this.http.get(`/api/users/${userId}`)
.pipe(
map(response => response.json()),
mergeMap(user =>
this.http.get(`/api/users/${userId}/posts`)
.pipe(
map(postsResponse => ({
user: user,
posts: postsResponse.json()
}))
)
)
);
}
// Filter responses
getActiveUsers(): Observable<any[]> {
return this.http.get('/api/users')
.pipe(
map(response => response.json()),
map(users => users.filter(user => user.active))
);
}
}