在我的Angular2應用程序中,我有一個「目錄」和「購物車」,通過目錄組件+目錄服務和購物車組件+購物車服務在我的代碼中表示。應用程序組件的公共變量Angular2
我有我的目錄組件中的產品數組,我想從數組中添加項目到另一個(最初是空的)陣列是購物車陣列。
我的目錄組件代碼:
import { Component, OnInit } from '@angular/core';
import { CatalogService } from './catalog.service';
import { CartComponent } from '../cart/cart.component';//I want to use the "cart" array initialized there in the Cart 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){ }
ngOnInit(){
this.catalogService.getCatalogItems().subscribe(
(data) => this.catalog = data
);
}
getPrev(){
this.catalog.push(this.catalog[0]);
this.catalog.shift();
}
getNext(){
this.catalog.unshift(this.catalog[this.catalog.length-1]);
this.catalog.pop();
}
togglePopup(prod){
this.prod = prod;
this.visible = !this.visible;
this.image = prod.image;
this.title = prod.title;
this.description = prod.description;
}
toCart(prod){
this.cart.push(prod);//"cart" array of my Cart Component
}
}
我的購物車組件:
import { Component, OnInit } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.scss']
})
export class CartComponent implements OnInit {
constructor (private cartService: CartService, public cart: Cart[]){}//by "public cart: Cart[]" I make it available from anywhere in my app
ngOnInit(){
this.cartService.getCartItems();
}
}
我的目錄服務:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CatalogService {
constructor(private http: Http){ }
getCatalogItems() {
return this.http.get('../catalog.json')//there are some items in the "catalog.json"
.map((res) => res.json())
}
}
我的購物車服務:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CartService {
constructor(private http: Http){ }
getCartItems() {
return this.http.get('../cart.json')//there are no items initially in the "cart.json", I want to add items from Catalog array to the initialized "cart : Cart[]" array
.map(
(res) => res.json()
);
}
}
雖然我宣佈全球車變量(「公共車:車[]」中的車組件)和進口車組件到目錄組件,即車變量不存在有(在我的目錄組件),並且我無法將目錄中的商品添加到購物車中。
那麼,如何創建一個購物車陣列這將適用於整個應用程序?如果我添加/刪除不存在,我想要其他組件,我會使用該對象自動更新其實例的對象購物車。