Installation de json-server
npm install -g json-server
json-server est un utilitaire qui va nous permettre de simuler un server rest
A la racine du projet, ajouter le fichier db.json :
{ "locations": [ { "id": 0, "name": "Acme Fresh Start Housing", "city": "Chicago", "state": "IL", "photo": "/assets/example-house1.jpg", "availableUnits": 4, "wifi": true, "laundry": true }, { "id": 1, "name": "A113 Transitional Housing", "city": "Santa Monica", "state": "CA", "photo": "/assets/example-house2.jpg", "availableUnits": 0, "wifi": false, "laundry": true }, { "id": 2, "name": "Warm Beds Housing Support", "city": "Juneau", "state": "AK", "photo": "/assets/example-house3.jpg", "availableUnits": 1, "wifi": false, "laundry": false }, ] }
Lancer le serveur json
json-server --watch db.json
Mise à jour du service
Dans le fichier src/app/housing.service.ts
Ajouter la propriété url:
url = 'http://localhost:3000/locations';
Mise à jour des fonctions pour récupérer la donnée
Mettre à jour la fonction getAllHousingLocations:
async getAllHousingLocations(): Promise<HousingLocation[]> { const data = await fetch(this.url); return await data.json() ?? []; }
Mettre à jour la fonction getHousingLocationsById :
async getHousingLocationById(id: number): Promise<HousingLocation | undefined> { const data = await fetch(`${this.url}/${id}`); return await data.json() ?? {}; }
Version finale du service en utilisant fetch
Au final votre fichier de service doit ressembler à cela :
import { Injectable } from '@angular/core'; import { HousingLocation } from './housinglocation'; @Injectable({ providedIn: 'root' }) export class HousingService { url = 'http://localhost:3000/locations'; async getAllHousingLocations(): Promise<HousingLocation[]> { const data = await fetch(this.url); return await data.json() ?? []; } async getHousingLocationById(id: number): Promise<HousingLocation | undefined> { const data = await fetch(`${this.url}/${id}`); return await data.json() ?? {}; } submitApplication(firstName: string, lastName: string, email: string) { console.log(firstName, lastName, email); } }
Appels asynchrones du service
Dans src/app/home/home.component.ts :
constructor() { this.housingService.getAllHousingLocations().then((housingLocationList: HousingLocation[]) => { this.housingLocationList = housingLocationList; this.filteredLocationList = housingLocationList; }); }
Dans src/app/details/details.component.ts :
constructor() { const housingLocationId = parseInt(this.route.snapshot.params['id'], 10); this.housingService.getHousingLocationById(housingLocationId).then(housingLocation => { this.housingLocation = housingLocation; }); }
Service Angular HttpClient
Ce service est une alternative à "fetch". Il lui est préféré par les développeurs qui ont besoin d'opérer des tests unitaires. Il pemet notamment le "bouchonnage".
Le service HttpClient est utilisable dans une application dans la mesure où on l'a importé et ajouté en tant que provider au niveau de AppComponent.
Si le composant AppComponent est "standalone", cela donnera :
import { provideHttpClient } from '@angular/common/http'; import { bootstrapApplication } from '@angular/platform-browser'; bootstrapApplication(AppComponent, { providers: [provideHttpClient()] }).catch(err => console.error(err)); @Component({ selector: 'co-cards', template: `<h1>Cartes</h1>`, standalone: true }) export class CardsComponent { constructor(private http: HttpClient) {} }
Sinon, dans un module :
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [BrowserModule, HttpClientModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {}
Méthodes HttpClient
Le service HttpClient fournit toutes les méthodes essentielles pour communiquer avec un serveur. Toutes les méthodes ci-dessous construisent un observable qui, une fois souscrit, provoque l'exécution de la requête (GET/POST/PUT/DELETE/PATCH/HEAD) configurée sur le serveur. Voir les surcharges individuelles pour plus de détails sur le type de retour.
- get
- post
- put
- delete
- patch
- head