私はカタログコンポーネントとカートサービスを持っています。 カタログ(JSONに格納されたオブジェクトの配列)の商品をカートに追加したいとします。BehaviorSubject/Angular2で初期化されたグローバル変数での作業
私は商品を追加/削除するときにカートを動的に変更する必要があります。 そのため、{BehaviorSubject}を使用しようとしています。
カートサービス:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class CartService {
public cart = new BehaviorSubject(null);//my globally available Cart
}
、私は私のを使用するために何をすべきか:
import { Component, OnInit } from '@angular/core';
import { CatalogService } from './catalog.service';
import { CartService } from '../cart/cart.service';//my globally available Cart imported to the current component
@Component({
selector: 'catalog',
templateUrl: './catalog.component.html',
styleUrls: ['./catalog.component.scss']
})
export class CatalogComponent implements OnInit {
catalog: any;
image: any;
title: string;
description: string;
prod: any;
visible: boolean;
constructor(public catalogService: CatalogService, public cartService: CartService){ }
ngOnInit(){
this.catalogService.getCatalogItems().subscribe(
(data) => this.catalog = data
);
}
toCart(prod){
this.cartService.cart.subscribe((val) => {
console.log(val);
});
this.cartService.cart.push(prod);//I want to add new product to the Cart by this
}
}
しかし、コンソールには次のようなエラーがスローされますカート ia BehaviorSubject?
申し訳ありませんがコードを修正しました。更新された亜種をご覧ください –