Answer the question
In order to leave comments, you need to log in
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
}
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
}
}
Answer the question
In order to leave comments, you need to log in
The BehaviorSubject
object 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 questionAsk a Question
731 491 924 answers to any question