Ich habe Katalog Komponente und Warenkorb Service in meiner App. Und ich möchte Produkte aus meinem Katalog (Array von Objekten in JSON gespeichert) zu Cart hinzufügen.Arbeiten mit einer globalen Variablen initialisiert über BehaviorSubject/Angular2
Also, ich brauche meinen Warenkorb dynamisch geändert werden, wenn ich ein Produkt hinzufügen/entfernen. Aus diesem Grund versuche ich {BehaviorSubject} zu verwenden.
Warenkorb Service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class CartService {
public cart = new BehaviorSubject(null);//my globally available Cart
}
Katalog Komponente:
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
}
}
Aber Konsole führt den folgenden Fehler:
Also, was soll ich tun, um meine zu verwenden Einkaufswagen global v ia BehaviourSubject?
Sorry, korrigiert den Code. Bitte sehen Sie sich die aktualisierte Variante an –