Angular
HttpClient & RxJS
Perform typed HTTP requests with HttpClient and Observables.
By EZ4Code Team
httprxjs
Code
import { Injectable, inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
export interface User { id: number; name: string; }
@Injectable({ providedIn: "root" })
export class UserApi {
private http = inject(HttpClient);
private base = "/api/users";
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.base);
}
create(user: Omit<User, "id">): Observable<User> {
return this.http.post<User>(this.base, user);
}
}
// Component usage:
// api.getUsers().subscribe(users => this.users = users);Explanation
HttpClient performs typed HTTP requests and returns RxJS Observables. Generic type arguments describe the response shape so subscribers get fully typed data. Observables are cold and single-request; use subscribe to execute and consider takeUntil to avoid memory leaks.
More Angular Snippets
Component Basics
Define an Angular component with selector, template, and styles.
Template Syntax & Binding
Interpolation, property, event, and two-way binding in Angular templates.
Built-in Directives
Use *ngIf, *ngFor, ngClass, and ngStyle to shape the DOM.
Pipes & Custom Pipe
Transform template values with built-in and custom pipes.
Services & Dependency Injection
Create an injectable service and consume it in a component.
Routing Configuration
Define routes with params, lazy loading, and redirects.