import {Component} from '@angular/core'; import {Car} from "../core/model/car"; import {MatSnackBar} from "@angular/material/snack-bar"; const CAR: Car = { id: 1, brand: 'Toyota', model: 'Yaris', power: 12, numberOfSeats: 5 }; @Component({ selector: 'app-promises-example', templateUrl: './promises-example.component.html', styleUrls: ['./promises-example.component.scss'] }) export class PromisesExampleComponent { car?: Car; isLoading: boolean = false; isLoaded: boolean = false; numberOfLoadings: number = 0; constructor( private snackBar: MatSnackBar ) { } // ****************************************** // Mode Promise avec les then/catch/finally // ****************************************** showCarViaAPromise(): void { this.loadCarViaAPromise(); } private loadCarViaAPromise(): void { this.isLoading = true; this.isLoaded = false; this.findViaPromise() .then(car => { this.car = car; this.isLoaded = true; }) .catch(error => { this.snackBar.open(`Error while loading car. Cause : ${error}`); }) .finally(() => { this.isLoading = false; this.numberOfLoadings++; }); } private findViaPromise(): Promise { return new Promise((resolve, reject) => { if (this.numberOfLoadings % 2 === 0) { setTimeout(() => { resolve(CAR); }, 2000); } else { reject('It\'s an odd call number.'); } }); } // ****************************************** // Mode async/await // ****************************************** showCarViaAsyncAwaitProcess(): void { this.loadCarViaAsyncAwaitProcess(); } private async loadCarViaAsyncAwaitProcess(): Promise { this.isLoading = true; this.isLoaded = false; try { this.car = await this.findViaAsyncAwaitProcess(); this.isLoaded = true; } catch (error) { this.snackBar.open(`Error while loading car. Cause : ${error}`); } this.numberOfLoadings++; this.isLoading = false; } private async findViaAsyncAwaitProcess(): Promise { if (this.numberOfLoadings % 2 !== 0) { throw 'It\'s an odd call number.'; } await new Promise(resolve => setTimeout(resolve, 2000)); return CAR; } }