Angular: HttpClient API
permet d'exécuter les méthodes (HTTP POST, GET, PUT, and DELETE)
Le fichier db.json est Créer contenant:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
Resources
http://localhost:3004/posts
http://localhost:3004/comments
http://localhost:3004/profile
Tester l'api
On peut executer les requests http sur l'api comme:
Get :http://localhost:3004/posts =>Afficher la liste des posts
Get:http://localhost:3004/posts/1 =>Afficher les détails d'un post passé en pramètre
Post:http://localhost:3004/posts =>Ajouter un nouveau post
Delete:http://localhost:3004/posts/1=>Suprimer un post
Put:http://localhost:3004/posts/1=>Modifier un post


1.Créer des components
Afin de gérer les posts ,ajouter,afficher,modifier,supprimer on doit créer les components correpondants:1.Créer un services qui permet de comsomer l'api
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PostServicesService {
constructor() { }
}
Ajouter le code suivante:
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class Post {
id?: string;
title?: string;
author?: string;
}
@Injectable({
//le services sera une seule instance dans tout le projet
providedIn: 'root'
})
export class PostServicesService {
api = 'http://localhost:3004';
constructor(private httpClient: HttpClient) {}
httpHeader = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
getPosts(): Observable<Post> {
return this.httpClient
.get<Post>(this.api + '/posts');
}
}
import { Component, OnInit } from '@angular/core';
import { PostServicesService } from '../mesServices/post-services.service';
@Component({
selector: 'app-listpost',
templateUrl: './listpost.component.html',
styleUrls: ['./listpost.component.css']
})
export class ListpostComponent implements OnInit {
posts: any = [];
constructor(public postServicesService: PostServicesService) {}
ngOnInit() {
this.getPosts();
}
getPosts() {
return this.postServicesService.getPosts().subscribe((res: {}) => {
this.posts = res;
});
}
}
<div class="card text-dark mb-3">
<div class="card-header card bg-warning text-white">List Posts</div>
<div class="card-body">
<table class="table table-striped">
<tr>
<th>id</th>
<th>Title</th>
<th>Author</th>
</tr>
<tr *ngFor="let p of posts; let i=index">
<td>{{p.id}}</td>
<td>{{p.title}}</td>
<td>{{p.author}}</td>
<td><a href="/posts/{{p.id}}">Détails</a></td>
</tr>
</table>
</div>
</div>
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ListComponent } from './list/list.component';
import { DetailsComponent } from './details/details.component';
import { ClientsComponent } from './clients/clients.component';
import { UsersComponent } from './users/users.component';
import { ListpostComponent } from './listpost/listpost.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'list',component: ListComponent } ,
{ path: 'clients',component: ClientsComponent } ,
{ path: 'users',component: UsersComponent } ,
{ path: 'listpost',component: ListpostComponent } ,
{ path: 'details/:id', component: DetailsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Supprimer un post
Ajouter la fonction supprimerPost()
supprimerPost(id: any) {
return this.httpClient
.delete<Post>(this.api + '/posts/' + id, this.httpHeader);
}
Ajouter la fonction supprimerPost()
supprimerPost(id: any) {
if (window.confirm('Confim?')) {
this.postServicesService.supprimerPost(id).subscribe((res) => {
this.getPosts();
});
}
}
Appeler la fonction supprimerPost()
<div class="card text-dark mb-3">
<div class="card-header card bg-warning text-white">List Posts</div>
<div class="card-body">
<table class="table table-striped">
<tr>
<th>id</th>
<th>Title</th>
<th>Author</th>
<th>Action</th>
</tr>
<tr *ngFor="let p of posts; let i=index">
<td>{{p.id}}</td>
<td>{{p.title}}</td>
<td>{{p.author}}</td>
<td><a href="/posts/{{p.id}}">Détails</a>
<td><button class="btn-danger btn-sm btn" style="background:red;" (click)="supprimerPost(p.id)">Supprimer</button></td>
</tr>
</table>
</div>
</div>

Details d'un post
Ajouter la fonction detailPost()
detailsPost(id: any): Observable<Post> {
return this.httpClient
.get<Post>(this.api + '/posts/' + id);
}
Ajouter la fonction detailPost()
import { Component, OnInit } from '@angular/core';
import { PostServicesService } from '../mesServices/post-services.service';
import { ActivatedRoute,ParamMap } from '@angular/router';
@Component({
selector: 'app-detailspost',
templateUrl: './detailspost.component.html',
styleUrls: ['./detailspost.component.css']
})
export class DetailspostComponent implements OnInit {
post: any = {};
constructor(private postServicesService: PostServicesService,private route:ActivatedRoute) {}
id:number=0;
ngOnInit(): void {
this.route.paramMap.subscribe((params: ParamMap) => {
this.id = Number(params.get('id'));
this.detailsPost(this.id);
console.log(this.post);
})
}
detailsPost(id:any) {
return this.postServicesService.detailsPost(id).subscribe((res: {}) => {
this.post = res;
});
}
}
<div class="card text-dark mb-3">
<div class="card-header card bg-warning text-white">Details:{{post.title}}</div>
<div class="card-body">
<table class="table table-striped">
<tr>
<th>id</th>
<th>Title</th>
<th>Author</th>
<th>Action</th>
</tr>
<tr>
<td>{{post.id}}</td>
<td>{{post.title}}</td>
<td>{{post.author}}</td>
</tr>
</table>
</div>
</div>
Ajouter la route
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ListComponent } from './list/list.component';
import { DetailsComponent } from './details/details.component';
import { ClientsComponent } from './clients/clients.component';
import { UsersComponent } from './users/users.component';
import { ListpostComponent } from './listpost/listpost.component';
import { DetailspostComponent } from './detailspost/detailspost.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'list',component: ListComponent } ,
{ path: 'clients',component: ClientsComponent } ,
{ path: 'users',component: UsersComponent } ,
{ path: 'listpost',component: ListpostComponent } ,
{ path: 'details/:id', component: DetailsComponent } ,
{ path: 'posts/:id', component: DetailspostComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Ajouter un post
Ajouter la fonction ajouterPost()
ajouterPost(post: any): Observable<Post> {
return this.httpClient.post<Post>(
this.api + '/posts',
JSON.stringify(post),
this.httpHeader
);
}
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PostServicesService } from '../mesServices/post-services.service';
@Component({
selector: 'app-addpost',
templateUrl: './addpost.component.html',
styleUrls: ['./addpost.component.css']
})
export class AddpostComponent implements OnInit {
post = { id: 0, title: '', author: ''}
constructor(
public postServicesService: PostServicesService,
public router: Router
) { }
ngOnInit(): void { }
ajouterPost(data: any) {
this.postServicesService.ajouterPost(this.post).subscribe((data: {}) => {
this.router.navigate(['/listpost'])
})
}
}
<div class="card text-dark mb-3">
<div class="card-header card bg-success text-white">Ajouter un nouveau post</div>
<div class="card-body">
<div class="form-group">
<input type="text" [(ngModel)]="post.title" class="form-control" placeholder="title">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="post.author" class="form-control" placeholder="author">
</div>
<div class="form-group">
<input type="number" [(ngModel)]="post.id" class="form-control" placeholder="id">
</div>
<div class="form-group">
<button class="btn btn-info btn-sm form-control" (click)="ajouterPost(post)">Valider</button>
</div>
</div>
</div>
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ListComponent } from './list/list.component';
import { DetailsComponent } from './details/details.component';
import { ClientsComponent } from './clients/clients.component';
import { UsersComponent } from './users/users.component';
import { ListpostComponent } from './listpost/listpost.component';
import { DetailspostComponent } from './detailspost/detailspost.component';
import { AddpostComponent } from './addpost/addpost.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'list',component: ListComponent } ,
{ path: 'clients',component: ClientsComponent } ,
{ path: 'users',component: UsersComponent } ,
{ path: 'listpost',component: ListpostComponent } ,
{ path: 'details/:id', component: DetailsComponent } ,
{ path: 'posts/:id', component: DetailspostComponent },
{ path: 'post/add', component: AddpostComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
