koque
koque

Reputation: 2256

Angular 2 -- Service not maintaining data

In the code below, the CartService class has a Cart class. CartItem(s) stored in the cart through the addToCart() function are displayed to the console to show that this functionality works.

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

export class CartItem {

  constructor(private product: Product, private quantity: number) { }

  public increaseQuantity() {
    this.quantity++;
  }

  public getProduct(): Product {
    return this.product;
  }
}

export class Cart {
  private cartItems: CartItem[] = [];
  private numberOfItems = 0;

  public addToCart(newProduct: Product) {
    let existingItem: CartItem = this.findProduct(newProduct._id);

if (existingItem) {
  existingItem.increaseQuantity();
} else {
  this.cartItems.push(new CartItem(newProduct, 1));
  this.numberOfItems++;
}
    console.log('Cart.cartItems = ', this.cartItems);
  }

  public getNumberOfItems(): number {
    return this.cartItems.length;
  }

  private findProduct(id): CartItem {
    for (let item of this.cartItems) {
      if (item.getProduct()._id == id) {
        return item;
      }
    }
    return null;
  }

  public getCartItems() {
    console.log('Cart.before return cartItems', this.cartItems)
    return this.cartItems;
  }
}

@Injectable()
export class CartService {
  private cart: Cart = new Cart();

  constructor() { }

  public addToCart(product:Product) {
    this.cart.addToCart(product);
  }

  public getNumberOfItems(): number {
    return this.cart.getNumberOfItems();
  }

  public getCartItems() {
    return this.cart.getCartItems();
  }
}

The problem is in the CartComponent class shown below, when the CartItem(s) of the Cart class are retrieved, they are showing no items in the cart. Somehow the items that were stored in the cart in the code above disappear.

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css'],
  providers: [CartService]
})
export class CartComponent implements OnInit {
  cartItems:CartItem[];

  constructor(private cartService:CartService) { }

  ngOnInit() {
    this.cartItems = this.cartService.getCartItems();
    console.log('CartComponent.cartItems', JSON.stringify(this.cartItems))
  }

}

Upvotes: 1

Views: 40

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657238

I suspect the cause is that you provide the service on CartComponent. When the component gets destroyed and recreated, a new service instance is created.

Instead provide it on AppModule

@NgModule({
  providers: [CartService, ...]
})
export class AppModule {}

to get an app-wide singleton with the same lifetime as the Angular application.

Upvotes: 3

Related Questions