S
S
Skrolea2016-02-15 20:03:27
Angular
Skrolea, 2016-02-15 20:03:27

How to update a variable in another component after adding?

Good afternoon. I want to add products to the service and so that in the header (and this is another component) the amount of added is updated.
Here is my service (well, quite ordinary)

import {Injectable} from 'angular2/core';
import {PRODUCTS} from '../components/products';
import {Product} from '../components/products';

export interface Cart  {
  id: Number;
  name: String;
}


@Injectable()
export class ProductService {
public products;
public cart : Cart[] = [];
  getProducts() {
  return Promise.resolve(PRODUCTS);
  }
  addToCart(products: Product) {
      this.cart.push(products);
  }
  getCart() {
    return this.cart;
  }
  getCartLength() : number {
    return this.cart.length;
  }
                            }

and here is the header
import {Component} from 'angular2/core';
import {ProductsCmp} from '../products/components/products';
import {ProductService} from '../products/services/products-services';

@Component({
  selector: 'header',
  templateUrl: './header/header.html',
  directives: [ProductsCmp],
  styleUrls: ['./header/header.css'],
  providers: [ProductService]
})
export class HeaderCmp {
  constructor(public product:ProductService) {}
}

But how can I update the variable in the header, which is called like this
<p>{{product.getCartLength()}}</p>
when I add something else to the cart?
The header component is connected to my app
<header></header>
  <router-outlet></router-outlet>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question