jrywin
jrywin

Reputation: 197

Correct refreshing of values using rxjs in Angular

I am wondering how to properly refresh the data in the component if there is any update. In my main panel I have a cart tab which displays the current number of products in the cart This is retrieved using endpoint from the backend

My navigation-cart component:

@Component({
  selector: 'navigation-cart',
  templateUrl: './navigation-cart.component.html',
  styleUrls: ['./navigation-cart.component.scss']
})
export class NavigationCartComponent extends implements OnInit {


  private cartItemCount$: Observable<Number>;

  public cartItemsCount: number;

  constructor(
    public eventbus: EventBusService,
    public cartService: CartService
    ) {
    this.eventbus.on('refreshCartCount', (state: any) => {
      console.log('maybe i should refresh here')

    });
  }
  ngOnInit() {
    this.cartItemCount$ = this.cartService.cartItemCount();
    this.cartItemCount$.subscribe(cartCount => {
      console.log(cartCount['productsCount'])
      this.cartItemsCount = cartCount['productsCount']
    }
    )
  }
}

property cartItemsCount is current number of items in cart from backend.

cartService:

@Injectable({
  providedIn: 'root'
})
export class CartService {
 

  public cartItemCount(): Observable<Number> {
    console.log('cartItemCount')
    return this.http.get<any>(`http://localhost:8000/basket/count`);
  }

}

If I add a product to the cart in another component how do I update the number of items in the cart?

  1. When adding a product to the cart should I emit an event that I catch in my component? How this emit should look like?

  2. Using Ngrx to store the current status of the cart:

ngOnInit(){    
store.dispatch(new cartCount());
}

and every update update this value

I'm just getting started with angular. How should it be done properly?

Upvotes: 1

Views: 458

Answers (1)

vaira
vaira

Reputation: 2270

On first page load you can get it from API service, but after that you have to subscribe from Subject to get alert for how many items are added.

You should pass an object with all the information about the product being added.

cartService.ItemAdded$.next(item)

Upvotes: 1

Related Questions