2016-09-14 60 views
1

这是我的第一个Angular应用程序,它基于tutorialAngular2服务不支持数据

我创建了一个CartService来管理我的购物车,CartComponent显示在我的导航栏中,以及CartReviewComponent用于查看购物车。

CartService位于app.module.ts的提供程序阵列中。 我相信,这实质上是创建一个单身人士。

NavbarComponent是在带路由的app.component.html文件中。

当产品添加到购物车时,导航栏中的CartComponent会观察更改并更新以显示总额$。

只要我路由到别的地方(另一页,或购物车审查),那么导航栏中的CartComponent显示一个空的购物车。

如何获取数据以便保存在购物车中,因此当我更换购物车时,购物车不是空的?

谢谢。

这里的CartService

import {Injectable} from "@angular/core"; 
import {OrderedItem} from "../models/OrderedItem"; 
import {Subject} from "rxjs/Subject"; 


@Injectable() 

export class CartService { 

private orderedItems: OrderedItem[] = []; 

//observable number sources 
private cartPriceTotalSource = new Subject<number>(); 
private cartItemTotalSource = new Subject<number>(); 

//observable number streams 
cartPriceTotal$ = this.cartPriceTotalSource.asObservable(); 
cartItemTotal$ = this.cartItemTotalSource.asObservable(); 

//message commands 
addToCart(item: OrderedItem) { 
    this.orderedItems.push(item); 
    this.calculateCartTotals(); 
} 

private calculateCartTotals() 
{ 
    let items = 0; 
    let price = 0; 

    this.orderedItems.forEach((element) => { 
     items += element.quantity; 
     price += element.quantity * element.item.price; 
    }); 

    this.cartItemTotalSource.next(items); 
    this.cartPriceTotalSource.next(price); 
} 

} 

******* ********** UPDATE

这里的CartComponent

import {Component} from "@angular/core"; 
import {OrderedItem} from "../../models/OrderedItem"; 
import {CartService} from "../../services/cart.service"; 


@Component({ 
    selector: "my-cart", 
    templateUrl: "app/components/cart/cart.component.html", 
    styleUrls: ["app/components/cart/cart.component.css"] 
}) 

export class CartComponent { 

    itemTotal: number = 0; 
    priceTotal: number = 0; 

    constructor(
     private cartService: CartService 
    ) { 
     cartService.cartItemTotal$.subscribe(
      itemTotal => this.itemTotal = itemTotal 
     ); 

     cartService.cartPriceTotal$.subscribe(
      priceTotal => this.priceTotal = priceTotal 
     ); 
    } 
} 
+0

您确定您没有'CartService'添加到'providers:[]'除'app.module.ts'外的任何地方吗?不要将它添加到任何'@Component({providers:[...])'。 –

+0

是的,无处不在,但'app.module.ts'。 – MayNotBe

+0

您可以向我们展示CartComponent吗? – Riv

回答

2

所有上面发布的代码似乎是正确的(或者现在足够正确)。

我的麻烦是我用href="the-defined-route"导航我的路线。

正确的方法是访问[routerLink]指令是这样的:

[routerLink]="['/the-defined-route']"

我意识到href方式是创造,也许是整个导航栏服务类的新实例。

如果任何人都可以解释到底发生了什么,我将不胜感激。