Use ingredients from API, recipes from localStorage
continuous-integration/drone/push Build is passing Details

main
Clément FRÉVILLE 11 months ago
parent ad3e268550
commit e59795dc35

@ -51,7 +51,13 @@
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
},
"defaultConfiguration": "production"

@ -1,5 +1,6 @@
import { Injectable } from '@angular/core';
import { Ingredient, Recipe } from '../cookbook/type';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root',
@ -36,6 +37,23 @@ export class RecipeService {
{ id: 2, name: 'Farine' },
];
constructor() {
if (environment.API_URL) {
fetch(environment.API_URL)
.then((response) => response.json())
.then((data) => {
for (const ingredient of data) {
ingredient.id = parseInt(ingredient.id);
}
this.#ingredients.push(...data);
});
}
const localRecipes = localStorage.getItem('recipes');
if (localRecipes) {
this.#recipes = JSON.parse(localRecipes);
}
}
getAll(): Recipe[] {
return this.#recipes;
}
@ -58,6 +76,7 @@ export class RecipeService {
id,
...recipe,
});
this.syncRecipes();
}
edit(recipe: Recipe): void {
@ -66,6 +85,21 @@ export class RecipeService {
this.#recipes[i] = recipe;
}
}
this.syncRecipes();
}
delete(recipe: Recipe): boolean {
const index = this.#recipes.findIndex((v) => v.id === recipe.id);
if (index === -1) {
return false;
}
this.#recipes.splice(index, 1);
this.syncRecipes();
return true;
}
syncRecipes() {
localStorage.setItem('recipes', JSON.stringify(this.#recipes));
}
addIngredient(ingredient: Omit<Ingredient, 'id'>) {

@ -34,6 +34,10 @@
</li>
</p>
</div>
<div>
<button mat-button (click)="delete()" color="warn">Supprimer</button>
</div>
</div>

@ -2,7 +2,7 @@ import { CommonModule } from '@angular/common';
import { Component, Input } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { RouterLink } from '@angular/router';
import { Router, RouterLink } from '@angular/router';
import { Recipe } from '../../cookbook/type';
import { RecipeService } from '../recipe.service';
@ -20,6 +20,11 @@ export class RecipeComponent {
this.recipe = this.recipes.get(parseInt(id))!;
}
constructor(protected recipes: RecipeService) {
constructor(protected recipes: RecipeService, private router: Router) {
}
delete(): void {
this.recipes.delete(this.recipe);
this.router.navigateByUrl('/recipes');
}
}

@ -0,0 +1,3 @@
export const environment = {
API_URL: 'https://664ba07f35bbda10987d9f99.mockapi.io/api/ingredients',
};

@ -0,0 +1,3 @@
export const environment = {
API_URL: 'https://664ba07f35bbda10987d9f99.mockapi.io/api/ingredients',
};
Loading…
Cancel
Save