我是Angular 2的新手,我仍然在想办法。 我有两个组成部分:
1)列出组件
列出商店中的所有商品并执行其他功能
@Component({
selector :'home-list',
providers :[CartService,CartStatus]
})
@View({
templateUrl :'/app/views/list-product.partial.html'
})
export class HomeList{
title: string;
products : ProductInterface[];
cart;
private isFetching: boolean = false;
constructor(
private _router : Router,
private _dataService: DataService,
private _cartService: CartService,
private _cartStatus: CartStatus
){}
ngOnInit(){
this.title = 'Featured Products';
this.getfeaturedproducts();
}
getfeaturedproducts(){
this._dataService.getFeatured().subscribe(
products => {
this.products = products;
this.isFetching = true;
}
)
}
gotoDetail(slug:string) {
console.log(slug);
this._router.navigate(['ProductsDetail', {productslug:slug}]);
return false;
}
getCart(){
this._cartService.getCartContent().subscribe(
res => {
this.cart = res;
console.log(res.result)
}
);
}
addtoCart(id:number){
this._cartService.addToCart(id).subscribe(
res => console.log(res)
this._cartStatus.updateCart(id);
//want to pass the data to CartStatus Component
)
}
}
2)CartUpdate组件,显示购物车中没有商品
@Component({
selector : 'cart-status'
})
@View({
template :'{{cart}}'
})
export class CartStatus{
cart;
updateCart(id:number){
this.cart = id;
}
}
问题是我无法将id或任何值传递给CartStatus视图。当我在console.log上调用updateCart上的id时,它会显示准确的值但不会反映CartStatus的视图。
我在这里做错了吗?
答案 0 :(得分:1)
从您的代码中,我可以看出CartStatus
是一个组件,所以,
providers :[CartService,CartStatus]
应该是,
providers : [CartService]
directives : [cardStatus]
现在,查看这个官方文档,了解组件之间的通信,
https://angular.io/docs/ts/latest/cookbook/component-communication.html
答案 1 :(得分:0)
至于我,将物品添加到购物车对我来说并不容易实现。用户有物品(产品,数量,总价),用户已订购物品(物品,总数,总价格),用户登录,所有会话购物车物品被清除并添加到用户物品等。我使用MongoStore实现了我的购物车(具有到期日期的会话),这样当您刷新页面时,这些项目仍然存储在购物车中。 MongoStore是一个很长的主题,我在这里无法帮助你。在Utube上有一个教程(来自Udemy的MAX的角度1,以及我是如何学习它的)。老实说,我不知道如何存储"类对象"在LocalStorage中。有关如何将项目添加到购物车的学习目的是使用数组。
允许'创建一个Cart类:
export Class {
public product: Product;
public qty: number) {}
}
创建服务:cart.service.ts
import { Injectable } from '@angular/core';
import { Cart } from './cart';
import { Product } from './product';
@Injectable()
export class CartService {
private carts: Carts[];
getCart() {
return this.carts;
}
addToCart(product: Product) {
for(let i=0; i<this.carts.length; i++) {
if(this.carts[i].product.productId == product.productId) {
this.carts[i].quantity = this.carts[i].quantity + 1;
return;
}
let cart = new Cart(product, 1);
this.carts.push(cart;
}
}
getCartTotal(){
let total = 0;
for(let i=0; i<carts.length; i++) {
total = total + this.carts[i].quantity;
}
return total;
}
emptyCart() {
this.carts = [];
}
}
在您的购物车组件中:
export class CartStatus implements OnInit {
carts: Cart[];
constructor(private: _cartService: CartService) {
ngOnInit(){
this.carts = this._cartService.getCart(); //no subsribe() here since is not an http request.
}
请不要忘记将CartService添加到您的启动文件中。我希望这有帮助。我还可以帮助你使用deleteItem,updateItem和getTotalCost。谢谢和快乐编码..