Menggunakan Service Pada Project Buku Resep – Latihan

Setelah mempelajari Service untuk Recipe pada modul sebelumnya. Pada modul ini diharapkan Anda melakukan latihan.

Buat service untuk Shopping-List, dimana service akan menangani data dan fungsi add shopping list.

TIPS: Shopping-List service di registrasikan dalam scope aplikasi, jadi daftarkan di app.module.ts.

Nah, semoga latihan Anda sukses. Jika Ada masalah, silakan cek solusi yang kami sediakan.

Buat file shopping-list/shopping-list.service.ts, lalu masukan code berikut.

import { EventEmitter } from "@angular/core";
import { Ingredient } from "../shared/ingredient.model";

export class ShoppingListService{
    newInggredientAdded = new EventEmitter<Ingredient[]>();

    private ingredients : Ingredient[] = [
        new Ingredient("Oreo", 1),
        new Ingredient("Tepung", 1),
      ];    

    getIngredients(){
        return this.ingredients.slice();
    }

    addIngredient(ingredient : Ingredient){
        this.ingredients.push(ingredient);
        //untuk handling event ketika new ingredient ditambahkan.
        this.newInggredientAdded.emit(this.ingredients.slice());
    }
}

File shopping-list.component.ts

import { Component, OnInit } from '@angular/core';
import { Ingredient } from '../shared/ingredient.model';
import { ShoppingListService } from './shopping-list.service';

@Component({
  selector: 'app-shopping-list',
  templateUrl: './shopping-list.component.html',
  styleUrls: ['./shopping-list.component.css']
})
export class ShoppingListComponent implements OnInit {
  ingredients! : Ingredient[];

  constructor(private shoppingListServ : ShoppingListService) { }

  ngOnInit(): void {
    this.ingredients = this.shoppingListServ.getIngredients();
    this.shoppingListServ.newInggredientAdded.subscribe(
      (ingredients: Ingredient[]) =>{this.ingredients = ingredients;}
    );
  }

  //tidak digunakan sudah dipindah ke service.
  // onIngredientAdded(ingredient : Ingredient){
  //   this.ingredients.push(ingredient);
  // }

}

File shopping-list.component.html

<div class="row">
    <div class="col-xs-10">
        <!-- tidak digunakan sudah dipindah ke service -->
        <!-- <app-shopping-edit (ingredientAdded)="onIngredientAdded($event)"></app-shopping-edit> -->
        <app-shopping-edit></app-shopping-edit>
        <hr>
        <ul class="list-group">
            <a class="list-group-item" style="cursor:pointer" *ngFor="let ingredient of ingredients">
                {{ingredient.name}} ({{ingredient.amount}})
            </a>
        </ul>
    </div>
</div>

File shopping-edit.component.ts

//hapus eventEmitter dan Output module.
import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { Ingredient } from 'src/app/shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {
  @ViewChild('nameInput', {static:false}) nameInputRef!: ElementRef;
  @ViewChild('amountInput', {static:false}) amountInputRef!: ElementRef;
  //tidak digunakan, sudah dipindah ke service.
  //@Output() ingredientAdded = new EventEmitter<Ingredient>();

  constructor(private shoppingListServ : ShoppingListService) { }

  ngOnInit(): void {
  }

  onAddItem(){
    const _name = this.nameInputRef.nativeElement.value;
    const _amount = this.amountInputRef.nativeElement.value;
    const newIngredient = new Ingredient(_name, _amount);
    //tidak digunakan sudah dipindah ke service.
    //this.ingredientAdded.emit(newIngredient);
    this.shoppingListServ.addIngredient(newIngredient);
  }
}

Seperti yang sudah dibahas pada awal modul, service akan diregistrasikan pada level aplikasi.

File app.module.ts

import { NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RecipesComponent } from './recipes/recipes.component';
import { RecipeListComponent } from './recipes/recipe-list/recipe-list.component';
import { RecipeDetailComponent } from './recipes/recipe-detail/recipe-detail.component';
import { RecipeItemComponent } from './recipes/recipe-list/recipe-item/recipe-item.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';
import { ShoppingEditComponent } from './shopping-list/shopping-edit/shopping-edit.component';
import { DropDownDirective } from './shared/dropdown.directive';
import { ShoppingListService } from './shopping-list/shopping-list.service';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    RecipesComponent,
    RecipeListComponent,
    RecipeDetailComponent,
    RecipeItemComponent,
    ShoppingListComponent,
    ShoppingEditComponent,
    DropDownDirective
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [ShoppingListService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Nah, semoga dengan latihan ini, Anda semakin paham dalam menggunakan Service. Pada modul selanjutnya kita akan belajar passing data antar service.

Sharing is caring:

Leave a Comment