MayNotBe
MayNotBe

Reputation: 2140

Angular2 Service not persisting data

This is my first Angular app and it's based on the tutorial.

I created a CartService to manage my shopping cart, a CartComponent to show in my navbar, and a CartReviewComponent for reviewing the cart.

The CartService is in the providers array of the app.module.ts. This, I believe, essentially creates a singleton.

The NavbarComponent is in the app.component.html file with the routing.

When a product is added to the cart, the CartComponent in the navbar observes the change and updates to show the total $.

As soon as I route somewhere else (another page, or cart-review) then the CartComponent in the navbar shows an empty cart.

How can I get the data to persist in the cart so when I change pages the cart isn't empty?

Thanks.

Here's the 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**********

Here's the 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
        );
    }
}

Upvotes: 1

Views: 990

Answers (1)

MayNotBe
MayNotBe

Reputation: 2140

All the code posted above seems to be correct (or correct enough for now).

My trouble was that I was navigating my routes with href="the-defined-route".

The correct way is to access the [routerLink] directive like this:

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

I realize the href way was creating new instances of the service class and perhaps the entire navbar.

If anyone can explain exactly what was happening I would appreciate it.

Upvotes: 3

Related Questions