import { bootstrapApplication } from '@angular/platform-browser';
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { provideHttpClient, HttpClient, withInterceptors, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
// Fake HTTP interceptor so the demo works without external network calls
function mockHttp(req, next) {
if (req.method === 'POST' && req.url.includes('jsonplaceholder.typicode.com/posts')) {
const reqBody = req.body || {};
const body = { id: 101, ...reqBody };
return of(new HttpResponse({ status: 201, body }));
}
return next(req);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<h3>HTTPClient POST</h3>
<button (click)="createPost()" [disabled]="loading">Create Post</button>
<p *ngIf="loading">Sending...</p>
<p *ngIf="error" style="color:crimson">{{ error }}</p>
<div *ngIf="result">
<p>Created Post ID: {{ result.id }}</p>
<p>Title: {{ result.title }}</p>
</div>
`
})
export class App {
http = inject(HttpClient);
loading = false;
error = '';
result = null;
createPost() {
this.loading = true;
this.error = '';
this.result = null;
this.http.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
}).subscribe({
next: (res) => { this.result = res; this.loading = false; },
error: () => { this.error = 'Failed to create post'; this.loading = false; }
});
}
}
bootstrapApplication(App, { providers: [provideHttpClient(withInterceptors([mockHttp]))] });
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular HTTP POST</title>
</head>
<body>
<app-root></app-root>
</body>
</html>