Answer the question
In order to leave comments, you need to log in
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"
}
}
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();
}
}
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())
}
}
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()
);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question