【发布时间】:2017-02-05 18:51:15
【问题描述】:
我的应用中有目录组件和购物车服务。我想将我的 Catalog(存储在 JSON 中的对象数组)中的产品添加到 Cart。
因此,我需要在添加/删除产品时动态更改我的购物车。 出于这个原因,我尝试使用 { 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
}
}
那么,我应该怎么做才能通过 BehaviorSubject 在全局范围内使用我的 Cart?
【问题讨论】:
标签: angular typescript behaviorsubject