A
A
Alexander Belov2017-02-05 22:14:21
Angular
Alexander Belov, 2017-02-05 22:14:21

How to deal with global variable and BehaviorSubject / Angular2?

I have a Catalog Component and a Cart Service in my application. I need to add products from the Catalog Component (they are stored in an array of objects in JSON by default) to a Cart variable (initially empty array).
This Cart mass should change dynamically as a product is added/removed. I decided to use { BehaviorSubject } for this.
Cart Service:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class CartService {
  public cart = new BehaviorSubject(null);//my globally available Cart

}

Catalog Component:
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);//добавляю новый продукт в массив Cart
  }

}

The console gives an error:
16041192e95d4b628231d5b02b72a7c1.png
How to set up work with a global variable (array) Cart using BehaviorSubject?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2017-02-06
@yurzui

The BehaviorSubjectobject has a methodgetValue
You can see an example here https://github.com/jhades/angular2-rxjs-observable...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question