0

I have two components and 2 services connected to them. First is a ProductComponent:

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css'],
  providers: [ProductService, CartService]
})
export class ProductComponent implements OnInit {
  private products;
  private numberOfItems = 0;

  constructor(private productService: ProductService, private cartService: CartService) {
  }

  ngOnInit() {
    this.loadProducts();
  }

  loadProducts() {
    this.productService.getProducts().subscribe(data => this.products = data);
  }

  addProductToCard(product: Product) {
    this.cartService.addProduct(product);
    this.numberOfItems = this.cartService.getCartLength();
  }
}

I use here CartService where I saved products I want to buy. All of them are add into cart list which is defined in CartService:

@Injectable()
export class CartService {
  private cart: Product[] = [];

  constructor() {
  }

  addProduct(product: Product) {
    this.cart.push(product);
  }

  getCart() {
    return this.cart;
  }

  getTotalPrice() {
    const totalPrice = this.cart.reduce((sum, cardItem) => {
      return sum += cardItem.price, sum;
    }, 0);
    return totalPrice;
  }

  getCartLength() {
    return this.cart.length;
  }
}

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  amount: number;
}

Now I want to use this filled cart list in CartComponent:

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css']
})
export class CartComponent implements OnInit {

  private cart;

  constructor(private cartService: CartService) {
  }

  ngOnInit() {
    this.cart = this.cartService.getCart();
    console.log(this.cart.length);
  }    
}

but it is empty there. I know that probably I inject there new CartService, not that one I used in ProductComponent. My question is how to use same instance of CartService in CartComponent as I use in ProductComponent? Or how to share data between this two services? Maybe I should use cache for this but I hope there are other ways to solve this problem.

EDIT: I add html where I call addToProduct():

<div class="basket">
  On your cart {{numberOfItems}} items
  <p><a routerLink="/cart">Go to cart</a></p>
  <router-outlet></router-outlet>
</div>

<table class="table table-striped">
  <thead class="thead-inverse">
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Desc</th>
    <th>Price</th>
    <th>Amount</th>
  </tr>
  </thead>
  <tbody *ngFor="let product of products">
  <tr>
    <th scope="row">{{product.id}}</th>
    <td>{{product.name}}</td>
    <td>{{product.description}}</td>
    <td>{{product.price}}</td>
    <td>{{product.amount}}</td>
    <button type="button" class="btn btn-success" (click)="addProductToCard(product)">Add to cart</button>
  </tr>
  </tbody>
</table>
6
  • probably or not, you are not sure what you asking clarifies as off-topic because "clear problem statement" is required. Commented May 28, 2017 at 20:51
  • What is not clear in my question? I want to use same instance of service in two places. Commented May 28, 2017 at 20:52
  • Now I want to use this filled cart list in CartComponent - it is not filled yet. There's even no addProductToCard call in your code . See stackoverflow.com/help/mcve Commented May 28, 2017 at 21:03
  • It is, in ProductComponent I call addProductToCard(). Commented May 28, 2017 at 21:04
  • There is no this.addProductToCard() method call in code you've posted. Commented May 28, 2017 at 21:13

2 Answers 2

1

If you want to get the same instance of CartService in both components, You have to register it as a Module-level provider, not as a provider on the individual Components.

Sign up to request clarification or add additional context in comments.

1 Comment

And this is an answer. Yes, it works now. Thank you!
0

Sharing data between services is better approch. Instead use ngrx/store package which is similar to Redux.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.