这是使用Rails API的简单购物车应用程序。我的ShowComponent中有addToCart按钮和CartComponent。我有购物车主要功能的CartService。 这里是我的cart.service:无法从Angular 2的服务中获取数据
import {Injectable} from '@angular/core';
import {Item} from './cart/cart';
@Injectable()
export class CartService {
private cartItems:Item[] = [];
constructor() {}
getCart() {
return this.cartItems;
}
addToCart(pizza, qtyString:string = "1") {
let qty = Number(qtyString);
console.log(typeof qty, qty);
console.log(typeof pizza, pizza);
if (this.cartItems.length == 0) {
this.cartItems.push(new Item(pizza['title'], pizza['price'], qty));
console.log(this.cartItems);
} else {
for(let i = 0; i < this.cartItems.length; i++) {
if (this.cartItems[i].title == pizza.title) {
console.log(this.cartItems[i].qty);
this.cartItems[i].qty += qty;
return true;
};
}
this.cartItems.push(new Item(pizza.title, pizza.price, qty));
}
}
deleteItems(pizza) {
this.cartItems.splice(this.cartItems.indexOf(pizza), 1);
}
editItems(value, i) {
this.cartItems[i].qty = +value;
}
}
我用addToCart函数在我show.component.html添加项目和所有工作正常(我有在结果的所有数据对象)。但是当我尝试去购物车时,我无法获取这个数据(this.cartItems.length == 0)。这里是我的CartComponent:
import {Component, OnInit} from '@angular/core';
import {CartService} from '../cart.service';
import {Pizza} from '../pizza';
import {Item} from './cart';
import {Router} from '@angular/router';
@Component({
moduleId: module.id,
selector: 'app-cart',
templateUrl: 'cart.component.html',
styleUrls: ['cart.component.css']
})
export class CartComponent implements OnInit {
cartItems = [];
constructor(private cartService: CartService, private router: Router) {}
ngOnInit() {
this.cartItems = this.cartService.getCart();
console.log(this.cartItems.length);
}
getTotalPrice() {
let total = 0;
this.cartItems.forEach((pizza: any, i:number) => {
total += pizza.price * pizza.qty;
})
return total;
}
}
这里是我的项目模型:
export class Item {
constructor(public title:string, public price:number, public qty:number) {}
}
我应该做的就是它?谢谢
感谢您的回答。提供商加入到AppComponent:'进口{CartService}从 './cart.service';' '@Component({ 提供商:[PizzaService,CartService] })' '出口类AppComponent {}' – Ujin