ビール片手にプログラム ~ そうだ!遊ぼう! ~

ただ飲みながら遊んでいる話。まじめなこととかはしません。

Angular.jsのチュートリアルをして遊ぼう ④サービス

今回は前回の続きでAngular.jsの公式サイトのチュートリアルのサービスの箇所を実施して遊ぼうと思います。
前回の記事で使用したコードを前提に作成していきますので、まず前回の記事から見ていただいたほうが良いかと思います。

1. 今日のお供

エビスのプレミアムエールです。
サッポロ ヱビス プレミアム [ 350ml×24本 ]

2. 今回参考にしたサイト

私はただ備忘録として、遊んだ結果を書きたいだけなので、本気でやりたい方はこちらを参考にされたほうが良いかと思います。

angular.jp

3. カートサービスを作成する

今回は商品の詳細ページに[購入]ボタンを追加し、商品に関する情報をカートに保存するためのカートサービスを作成していきます。

まずはカートのサービスを作成します。

f:id:front-end:20190608115058p:plain
サービスを選択

cartと入力して。。

f:id:front-end:20190608115154p:plain
cart

cartサービスが作成されました。

f:id:front-end:20190608115306p:plain
cartサービス

4. カートサービスを定義する

カートサービスに商品の追加・商品の参照・商品の削除が出来るよう設定していきます。

(1) どこからでもDIできるようにします。

@Injectable({
  providedIn: 'root'
})

f:id:front-end:20190608120027p:plain
DIの設定

(2) 商品情報格納用の配列を追加します。

items = [];

f:id:front-end:20190608120158p:plain
配列の追加

(3) 商品に対するメソッドを追加します。

  // 商品の追加
  addToCart(product) {
    this.items.push(product);
  }

  // 商品リストの取得
  getItems() {
    return this.items;
  }

  // 商品リストのクリア
  clearCart() {
    this.items = [];
    return this.items;
  }

f:id:front-end:20190608120511p:plain
メソッドの追加

5. カートサービスを使用する

商品詳細ページに購入ボタンを追加し、購入ボタンを押下した場合、カートサービスに商品が登録されるようにしていきます。

(1) 商品詳細ページがカートサービスを使用するよう設定します。

product-details.component.tsにカートサービスをインポートし、コンストラクタで注入します。

import { CartService } from '../cart.service';
  constructor(private route: ActivatedRoute,
              private cartService: CartService) { }

f:id:front-end:20190608121403p:plain
カートサービスのインポート

カートサービスに商品を追加するメソッドを追加します。(何故か下線が引かれていますが。。

  addToCart(product) {
    window.alert('Your product has been added to the cart!');
    this.cartService.addToCart(product);
  }

f:id:front-end:20190608125435p:plain
カートに追加

商品詳細画面に購入ボタンを追加します。

<button (click)="addToCart(product)">Buy</button>

f:id:front-end:20190608125618p:plain
購入ボタンを追加

(2) カートページを作成します。

まずはカートコンポートネントを作成して。。

f:id:front-end:20190608125742p:plain
カートコンポーネント

app.module.tsにカートコンポーネントのルーティング(URLパターン)を追加します。

{ path: 'cart', component: CartComponent },

f:id:front-end:20190608125914p:plain
app.module.ts

カートページにカートサービスの商品情報が表示されるように設定します。

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) { 
    this.items = this.cartService.getItems();
  }

  ngOnInit() {
  }

}

f:id:front-end:20190608130240p:plain
cart.component.ts

カート画面に商品情報を表示するよう設定します。

<h3>Cart</h3>

<div class="cart-item" *ngFor="let item of items">
  <span>{{ item.name }} </span>
  <span>{{ item.price | currency }}</span>
</div>

購入ボタンを押下するとカート画面に商品が追加されるようになりました。

f:id:front-end:20190608130827p:plain
カート画面完成!

6. サービスが使えました!

きちんと書いているのに、何故かエラーの下線がでたりしましたが、なんとか実装が完了しました。
とりあえず、Angularのチュートリアルはここまでとして、次回は何か違うことが出来たらいいなぁ。と思います。