วันพุธที่ 8 มกราคม พ.ศ. 2563

Angular 8 - บริการเก็บข้อมูลด้วย Service

การสร้าง Service ที่ใช้ในการจัดการข้อมูลต่าง ๆ ใน App ของเราใช้ Tutorial Guide จาก https://angular.io/start/data
ใน App ของเรานั้นจำเป็นต้องมี Service เอาไว้ใช้งาน เราสามารถใช้ในการจัดการข้อมูล และดึงข้อมูลจากแหล่งข้อมูลอื่น ๆ ผ่านทาง Service ได้ สำคัญมาก

สร้าง Service ชื่อ CartService ไว้เก็บข้อมูลการสั่งซื้อมือถือ ให้ใช้คำสั่ง "ng generate service cart" เสร็จแล้วเราจะได้ไฟล์มา 2 ไฟล์
1. "src/app/cart.service.spec.ts" และ 2. "src/app/cart.service.ts" เราจะเข้ามาแก้ไฟล์ที่ 2. นี่กัน
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class CartService {

  constructor() { }
}

ให้เราเพิ่ม Function 3 ตัวคือ addItem() ใช้เพิ่ม Item ลงตะกร้า , getItems() เรียกดูค่า Item ในตะกร้า และ clearItems() ลบ Item ออกจากตะกร้าทั้งหมด
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class CartService {

  items = [];

  addItem(product) {
    this.items.push(product);
  }

  getItems() {
    return this.items;
  }

  clearItems() {
    this.items = [];
  }

  constructor() { }

}

ทำการ Import CartService เพิ่มลงใน Constructor และสร้าง Function ในการ Add Item ลงตะกร้า และ View Item ในตะกร้า
import { Component, OnInit } from '@angular/core';

import { products } from '../static/products';
import { CartService } from '../cart.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})

export class ProductListComponent implements OnInit {

  title = 'Product List';
  productList = products;

  share() {
    window.alert("The product has been shared!");
  }

  add(product) {
    window.console.log(product);
    this.cartService.addItem(product);
  }

  view() {
    window.console.log(this.cartService.getItems());
  }

  onNotify() {
    window.alert('You will be notified when the product goes on sale');
  }

  constructor(private cartService: CartService) { }

  ngOnInit() {
  }

}

สุดท้ายสร้างปุ่ม Add [บรรทัดที่ 13-14] และ View [บรรทัดที่ 24-26] แล้วทดสอบการทำงาน
<h1>{{title}}</h1>

<div *ngFor="let product of productList; index as productId">
    <a [title]="'Description: ' + product.description" [routerLink]="['/product', productId]">
        {{product.name}}
    </a>

    <p *ngIf="product.description">
        {{product.description}}
    </p>

    <button (click)="add(product)">
        Add To Cart
    </button>

    <button (click)="share()">
        Share
    </button>

    <app-product-alerts [product]="product" (notify)="onNotify()"></app-product-alerts>

</div>

<button (click)="view()">
    View Cart
</button>

แสดงการ Add 2 Item แล้ว View Items




สร้างหน้า Cart เพื่อให้แสดง Items ที่อยู่ใน Cart Service ใช้คำสั่ง "ng generate component cart"
เปลี่ยนคำสั่ง View ใน Button View Cart ให้ไปที่หน้า Cart
<h1>{{title}}</h1>

<div *ngFor="let product of productList; index as productId">
    <a [title]="'Description: ' + product.description" [routerLink]="['/product', productId]">
        {{product.name}}
    </a>

    <p *ngIf="product.description">
        {{product.description}}
    </p>

    <button (click)="add(product)">
        Add To Cart
    </button>

    <button (click)="share()">
        Share
    </button>

    <app-product-alerts [product]="product" (notify)="onNotify()"></app-product-alerts>

</div>

<button [routerLink]="['/cart']">
    View Cart
</button>

ต่อมาทำการ Import Cart Service [บรรทัดที่ 3] ใน Cart Component, กำหนดตัวแปร Item ไว้รอรับข้อมูล [บรรทัดที่ 12],
เพิ่ม cartService ที่ Contructor [บรรทัดที่ 14] และดึงค่ามาลงที่ Items ที่ประกาศไว้ [บรรทัดที่ 17] แล้วเขียน Template เพื่อแสดงผล
import { Component, OnInit } from '@angular/core';

import { CartService } from '../cart.service';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {

  items;

  constructor(private cartService: CartService) { }

  ngOnInit() {
    this.items = this.cartService.getItems();
  }

}
<h1>Cart</h1>

<div class="cart-item" *ngFor="let item of items; index as itemId">
    <span>{{item.name}}</span>
    <span>{{item.price || currency }}</span>
</div>
สรุปอ่านแล้วทำให้เข้าใจ

ไม่มีความคิดเห็น:

แสดงความคิดเห็น