2016-09-14 59 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方式是創造,也許是整個導航欄服務類的新實例。

如果任何人都可以解釋到底發生了什麼,我將不勝感激。