A
A
Alexander Belov2017-02-05 00:36:04
Angular
Alexander Belov, 2017-02-05 00:36:04

How to display a variable in the global context in Angular2?

I have a "Catalog" and "Cart" components in my Angular2 application that also have a Catalog service and a Cart service.
There is an array with products in the Catalog component and I need to add them to the Cart array (initially empty) on click.
Catalog Component:

import { Component, OnInit } from '@angular/core';
import { CatalogService } from './catalog.service';
import { CartComponent } from '../cart/cart.component';//импортирую компонент, чтобы иметь доступ к массиву "cart" внути него

@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){ } 

ngOnInit(){

    this.catalogService.getCatalogItems().subscribe(
        (data) => this.catalog = data
    );
}

getPrev(){
    this.catalog.push(this.catalog[0]);
    this.catalog.shift();
}

getNext(){
    this.catalog.unshift(this.catalog[this.catalog.length-1]);
    this.catalog.pop();
}

 togglePopup(prod){
    this.prod = prod;
    this.visible = !this.visible;
    this.image = prod.image;
    this.title = prod.title;
    this.description = prod.description;
}

   toCart(prod){
     this.cart.push(prod);//добавляю продукт в массив "cart"
   }

}

Cart Component:
import { Component, OnInit } from '@angular/core';
import { CartService } from './cart.service';

@Component({
    selector: 'cart',
    templateUrl: './cart.component.html',
    styleUrls: ['./cart.component.scss']
})

export class CartComponent implements OnInit {

    constructor (private cartService: CartService, public cart: Cart[]){}//объявляя глобальную переменную "public cart: Cart[]" я предполагаю, что могу ссылаться теперь на неё из любой части приложения, куда импортирую CartComponent

    ngOnInit(){
        this.cartService.getCartItems();
    }
}

catalog service:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()
export class CatalogService {
    constructor(private http: Http){ }

  getCatalogItems() {
      return this.http.get('../catalog.json')//в массиве "catalog.json" есть объекты по умолчанию
      .map((res) => res.json())
  }
}

Cart Service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

@Injectable()
export class CartService {
   constructor(private http: Http){ }

  getCartItems() {
      return this.http.get('../cart.json')//пустой массив по умолчанию "cart.json", куда я хочу добавлять продукты Catalog Component
      .map(
        (res) => res.json()
      );
  }
}

Even though I have declared a global Cart variable ("public cart: Cart[]" in the Cart Component) and imported the Cart Component into the Catalog Component , this variable is not visible there.
How to create a single Cart array and declare its variable so that it is available globally throughout the application? That is, so that you can add / remove something from this array and changes in it happen immediately automatically (and all components referring to it immediately work with the already changed array, without new redefinitions).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2017-02-05
@AMar4enko

Make a service, in it BehaviorSubject, keep the basket in it, subscribe the components to it, all changes to the basket through the service

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question