尝试购买购物车添加按钮以填充存储产品阵列的购物车服务。问题是,我无法在我的购物车组件中更新我的购物车列表,因为我无法检测按钮/或阵列何时填满了新产品。而这又不会为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;
}
}
答案 0 :(得分:0)
在您的ShoppingCart组件中,您需要迭代products
而不是shoppingCart
:
<ul>
<li *ngFor='#product of products'> <------
{{product.title}}
<li>
</ul>
此外,您需要将ShoppingCartService
服务作为两个组件的共享服务。要没有问题,请确保在引导应用程序时指定它:
bootstrap(AppComponent, [ ShoppingCartService ]);