尝试获取购物车添加按钮以填充存储产品阵列的购物车服务。问题是,我无法在我的购物车组件中更新我的购物车列表,因为我无法检测按钮/或阵列何时已填充新产品。这反过来又不会为ngFor添加新产品。
我读过关于变化检测、区域、事件发射器的文章。只是不确定在这种情况下哪个是正确的...我在下面附上了我的代码
购物车按钮组件
import {Component, OnInit, Input, NgZone} from 'angular2/core'
import {ShoppingCartService} from './shopping-cart.service.js'
@Component({
selector: 'add-cart',
template:`<button (click)="addToCart(product)">ADD TO CART</button>`,
inputs: ['product']
})
export class AddCartComponent {
constructor(
private _shoppingCartService: ShoppingCartService
) {}
addToCart(product: any) {
console.log(this.product);
this._shoppingCartService.add(this.product)
}
}
购物车组件
import {Component, OnInit} from 'angular2/core';
import {ShoppingCartService} from './shopping-cart.service.js'
@Component({
selector: 'shopping-cart',
template:`
<div id="shopping-cart">
<ul>
<li *ngFor='#product of shoppingCart'>
{{product.title}}
<li>
</ul>
</div>
`
})
export class ShoppingCartComponent implements OnInit {
products: any[];
constructor(
privarte _shoppingCartService: ShoppingCartService;
) {}
ngOnInit() {
this.products = shoppingCartService.get();
}
}
购物车服务
import {Injectable} from 'angular2/core';
@Injectable()
export class ShoppingCartService {
products: any[];
constructor() {
this.products = [];
}
add(product: any){
this.products.push(product);
}
remove(index: number) {
if (index > -1) {
this.products.splice(index, 1);
}
}
clear() {
this.products = [];
}
get() {
return this.products;
}
}
在ShoppingCart组件中,您需要迭代产品
而不是shop pingCart
:
<ul>
<li *ngFor='#product of products'> <------
{{product.title}}
<li>
</ul>
此外,您需要将ShoppingCartService
服务作为两个组件的共享服务。要确保没有问题,请确保在引导应用程序时指定了它:
bootstrap(AppComponent, [ ShoppingCartService ]);