J'ai Catalogue Component et Panier Service dans mon application. Et je veux ajouter des produits de mon Catalogue (tableau d'objets stockés dans JSON) au Panier. Donc, j'ai besoin que mon panier soit changé dynamiquement lorsque j'ajoute/enlève un produit. Pour cette raison, j'essaie d'utiliser {BehaviorSubject}.Travailler avec une variable globale initialisée via BehaviorSubject/Angular2
Panier Service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class CartService {
public cart = new BehaviorSubject(null);//my globally available Cart
}
Catalogue des composants:
import { Component, OnInit } from '@angular/core';
import { CatalogService } from './catalog.service';
import { CartService } from '../cart/cart.service';//my globally available Cart imported to the current component
@Component({
selector: 'catalog',
templateUrl: './catalog.component.html',
styleUrls: ['./catalog.component.scss']
})
export class CatalogComponent implements OnInit {
catalog: any;
image: any;
title: string;
description: string;
prod: any;
visible: boolean;
constructor(public catalogService: CatalogService, public cartService: CartService){ }
ngOnInit(){
this.catalogService.getCatalogItems().subscribe(
(data) => this.catalog = data
);
}
toCart(prod){
this.cartService.cart.subscribe((val) => {
console.log(val);
});
this.cartService.cart.push(prod);//I want to add new product to the Cart by this
}
}
Mais Console jette l'erreur suivante:
Alors, que dois-je faire pour utiliser mon Panier dans le monde v ia BehaviorSubject?
Désolé, corriger le code. S'il vous plaît jeter un oeil à la variante mise à jour –