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?
When adding a product to the cart should I emit an event that I catch in my component? How this emit should look like?
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?