लोड हो रहा है...

HttpClient संदर्भ

HttpClient संदर्भ एंगुलर में HTTP अनुरोधों को प्रबंधित करने के लिए एक मुख्य सेवा है। यह डेवलपर्स को RESTful APIs के साथ असिंक्रोनस डेटा आदान-प्रदान करने, observable streams के माध्यम से डेटा फ्लो नियंत्रित करने और components के state management को कुशलतापूर्वक संभालने में सक्षम बनाता है। यह SPA (Single Page Applications) में डेटा प्राप्त करने, UI अपडेट करने और lifecycle hooks के माध्यम से बेहतर प्रदर्शन सुनिश्चित करने में अत्यंत महत्वपूर्ण है।
HttpClient का उपयोग GET, POST, PUT, PATCH और DELETE अनुरोधों के लिए किया जाता है। यह RxJS Observables के साथ मिलकर asynchronous डेटा streams को manage करता है, error handling करता है और retry strategies लागू करता है। डेवलपर्स सीखते हैं कि कैसे reusable components बनाए जाएँ, state mutations को रोका जाए और prop drilling जैसी common mistakes से बचा जाए।
इस संदर्भ के माध्यम से पाठक advanced concepts जैसे component architecture, lifecycle integration, performance optimization और secure API communication सीखेंगे। यह उन्हें modular और reactive component development में मार्गदर्शन करता है, जिससे real-world एंगुलर applications में HttpClient का प्रभावी उपयोग सुनिश्चित होता है।

मूल उदाहरण

typescript
TYPESCRIPT Code
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

interface User {
id: number;
name: string;
email: string;
}

@Component({
selector: 'app-user-list',
template: `     <h2>User List</h2>     <ul>       <li *ngFor="let user of users">{{ user.name }} - {{ user.email }}</li>     </ul>
`
})
export class UserListComponent implements OnInit {
users: User[] = [];

constructor(private http: HttpClient) {}

ngOnInit(): void {
this.fetchUsers().subscribe({
next: (data) => this.users = data,
error: (err) => console.error('Users loading failed', err)
});
}

fetchUsers(): Observable<User[]> {
return this.http.get<User[]>('[https://jsonplaceholder.typicode.com/users](https://jsonplaceholder.typicode.com/users)');
}
}

इस उदाहरण में UserListComponent HttpClient का उपयोग करके डेटा लोड करता है। constructor में HttpClient को inject किया गया है। ngOnInit lifecycle hook में fetchUsers() कॉल की जाती है, जो Observable लौटाती है। subscribe के माध्यम से डेटा और errors को handle किया जाता है। Template में *ngFor का उपयोग करके users array render की जाती है, जिससे UI efficiently update होता है।
यह उदाहरण type safety, asynchronous data handling और reactive component design को दर्शाता है। State mutations और prop drilling से बचते हुए, Angular Change Detection सुनिश्चित करता है कि UI केवल आवश्यक updates पर rerender हो। यह pattern real-world applications में reusable और maintainable components बनाने के लिए best practices को दर्शाता है।

व्यावहारिक उदाहरण

typescript
TYPESCRIPT Code
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

interface Post {
id: number;
title: string;
body: string;
}

@Component({
selector: 'app-post-list',
template: `     <h2>Posts</h2>     <ul>       <li *ngFor="let post of posts">{{ post.title }}</li>     </ul>     <div *ngIf="errorMsg" class="error">{{ errorMsg }}</div>
`
})
export class PostListComponent implements OnInit {
posts: Post[] = [];
errorMsg: string = '';

constructor(private http: HttpClient) {}

ngOnInit(): void {
this.loadPosts();
}

loadPosts(): void {
this.http.get<Post[]>('[https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts)')
.pipe(
catchError(err => {
this.errorMsg = 'Failed to load posts';
console.error(err);
return of([]);
})
)
.subscribe(data => this.posts = data);
}
}

Advanced एंगुलर Implementation

typescript
TYPESCRIPT Code
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

interface Todo {
id: number;
title: string;
completed: boolean;
}

@Injectable({
providedIn: 'root'
})
export class TodoService {
private apiUrl = '[https://jsonplaceholder.typicode.com/todos](https://jsonplaceholder.typicode.com/todos)';

constructor(private http: HttpClient) {}

getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.apiUrl, { headers: new HttpHeaders({ 'Accept': 'application/json' }) })
.pipe(
retry(3),
catchError(this.handleError)
);
}

private handleError(error: HttpErrorResponse) {
console.error('HTTP Error:', error);
return throwError(() => new Error('Error fetching todos. Please try again later.'));
}
}

import { Component, OnInit } from '@angular/core';
import { TodoService } from './todo.service';

@Component({
selector: 'app-todo-list',
template: `     <h2>Todo List</h2>     <ul>       <li *ngFor="let todo of todos">
{{ todo.title }} <span *ngIf="todo.completed">✔️</span>       </li>     </ul>     <div *ngIf="errorMsg">{{ errorMsg }}</div>
`
})
export class TodoListComponent implements OnInit {
todos: Todo[] = [];
errorMsg: string = '';

constructor(private todoService: TodoService) {}

ngOnInit(): void {
this.todoService.getTodos().subscribe({
next: (data) => this.todos = data,
error: (err) => this.errorMsg = err.message
});
}
}

HttpClient संदर्भ के लिए best practices में responsibilities को विभाजित करना शामिल है। Components केवल data दिखाएँ या Services को डेटा fetch करने दें। Observables asynchronous state handling में मदद करते हैं और unnecessary re-renders से बचाते हैं। Prop drilling और direct state mutations common mistakes हैं।
Performance optimization के लिए RxJS operators जैसे catchError, retry, tap का उपयोग करें। Caching strategies और Interceptors का उपयोग security और centralized error handling के लिए आवश्यक है। Angular के asynchronous patterns, lifecycle hooks और reactive state management techniques को follow करके, scalable और maintainable SPA विकसित की जा सकती है।

📊 संपूर्ण संदर्भ

एंगुलर Element/Method Description Syntax Example Notes
HttpClient get JSON data get<T>(url: string, options?: any) http.get<User[]>('url') Returns Observable of T
HttpClient POST data post<T>(url:string,body:any,options?) http.post<User>('url', user) Create new resource
HttpClient PUT update put<T>(url:string,body:any,options?) http.put<User>('url', user) Replace resource
HttpClient PATCH partial update patch<T>(url:string,body:any,options?) http.patch<User>('url',{name:'new'}) Partial update
HttpClient DELETE resource delete<T>(url:string,options?) http.delete<User>('url') Delete resource
HttpHeaders Set headers new HttpHeaders({key:value}) const headers = new HttpHeaders({'Authorization':'token'}) Immutable
HttpParams Query params new HttpParams().set('key','value') const params = new HttpParams().set('id','1') Immutable
HttpClient Generic request request(method:string,url:string,options?) http.request('GET','url') Flexible request method
HttpClient Interceptors Central request handling { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi:true } Centralized Request/Response handling
HttpClient withCredentials Send cookies get('url',{withCredentials:true}) Supports cross-site requests
HttpClient observe Response type observe:'response' http.get<User>('url',{observe:'response'})
HttpClient retry operator retry(n) this.http.get(...).pipe(retry(3)) Retry failed requests
HttpClient catchError operator catchError(fn) this.http.get(...).pipe(catchError(err=>of([]))) Error handling
HttpClient tap operator tap(fn) this.http.get(...).pipe(tap(data=>console.log(data))) Side effects without modifying stream
HttpClient unsubscribe unsubscribe() subscription.unsubscribe() Avoid memory leaks
HttpClient async pipe Template usage <div *ngFor="let item of items$ async">{{item.name}}</div>

📊 Complete एंगुलर Properties Reference

Property Values Default Description एंगुलर Support
withCredentials true false Send auth credentials Angular 4.3+
headers HttpHeaders none HTTP header object Angular 4.3+
params HttpParams none Query parameters Angular 4.3+
reportProgress true false Enable progress events Angular 4.3+
setHeaders {[name:string]:string} none Shortcut to set headers Angular 4.3+
setParams {[name:string]:string} none Shortcut to set params Angular 4.3+
context HttpContext none Context for interceptors Angular 14+
withCredentials boolean false Send cookies Angular 4.3+

HttpClient संदर्भ का अध्ययन developers को asynchronous data fetching, reactive state management और lifecycle hooks के advanced उपयोग से परिचित कराता है। Observables और service-based architecture components को reusable और maintainable बनाते हैं।
आगे के अध्ययन में Interceptors, caching strategies, RxJS operators और integration with Reactive Forms शामिल करना चाहिए। इन techniques के अभ्यास से performance, security और maintainability बेहतर होती है। Angular documentation, RxJS guides और community best practices इस learning path को सपोर्ट करते हैं।

🧠 अपने ज्ञान की परीक्षा करें

शुरू करने के लिए तैयार

अपने ज्ञान की परीक्षा करें

इस इंटरैक्टिव क्विज़ के साथ अपनी चुनौती लें और देखें कि आप विषय को कितनी अच्छी तरह समझते हैं

4
प्रश्न
🎯
70%
पास करने के लिए
♾️
समय
🔄
प्रयास

📝 निर्देश

  • हर प्रश्न को ध्यान से पढ़ें
  • हर प्रश्न के लिए सबसे अच्छा उत्तर चुनें
  • आप जितनी बार चाहें क्विज़ दोबारा दे सकते हैं
  • आपकी प्रगति शीर्ष पर दिखाई जाएगी