1

I've got a dynamic array which I want to render in the view of a component when some items added / removed inside.

The array is rendered by ngOnInit() method in my App Component (ts):

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

import '../style/app.scss';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
    cartItems: any;
    image: any;
    item: any;

  constructor(public cartService: CartService) { }

  ngOnInit(){
    this.cartService.cart$.subscribe((val) => {
        console.log(this.cartService.cartArr)//console shows the array properly, but nothing is shown in the view if I remove "console.log"
    });

  }

}

"The view" for the array inside my App Component (html):

<ul class="cart">
    <li class="cart__item" *ngFor="let item of cartArr">
       ...
    </li>
</ul>

My CartService:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class CartService {
    public cart$ = new BehaviorSubject(null);
    public cartArr = [];

   constructor(){ }

   public addToCart(prod) {
       this.cartArr.push(prod);
       this.cart$.next(this.cartArr);
   }
}

So I wonder how to render the array in the Component html and why my code isn't working outside the console?

1 Answer 1

3

Update:

As said @TuongLe in comment if you manually subscribe to your observable then you should to call unsubscribe in ngOnDestroy to prevent memory leak.

You can either

1) set array value:

cartItems: any[];

cartSubscription: Subscription;

ngOnInit() {
  this.cartSubscription = this.cartService.cart$.subscribe((val) => {
    this.cartItems = val;
  });
}

ngOnDestroy() {
  this.cartSubscription.unsubscribe();
}

view

*ngFor="let item of cartItems"

or

2) use async pipe like:

*ngFor="let item of cartService.cart$ | async"
Sign up to request clarification or add additional context in comments.

1 Comment

You should use the async pipe as Angular will automatically handle the unsubscribe() for you. If you go wit the option 1, remember to call unsubscribe() in the ngOnDestroy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.