I am new to Angular. I have a cart service and two un-related components - ProductList Component and Nav Component. I am subscribing to the service in both the components, updating the cart count in ProductList Component but the Nav Component is still showing the initial count instead of updated one. Can any one please help.
@Injectable()
export class CartService {
private initialCount = new BehaviorSubject<number>(0);
currentCount = this.initialCount.asObservable();
//cartCount : BehaviorSubject<number>= new BehaviorSubject<number>(0);
changeCount(count: number) : number {
this.initialCount.next(count);
console.log("count in cart service ::: "+count);
return count;
}
}
ProductList Component :
export class ProductListComponent{
count : number;
constructor(private _cartService : CartService){}
ngOnInit(){
this._cartService.currentCount.subscribe(count => this.count = count);
}
newCount() : number{
return this._cartService.changeCount(this.count + 1)
}
}
ProductList Component HTML:
<button (click)='newCount()'><i class="fa fa-shopping-cart">{{count}}</i></button>
Nav Component :
export class NavComponent implements OnInit {
count : number;
constructor(private _cartService : CartService){}
ngOnInit(){
this._cartService.currentCount.subscribe(count => this.count = count);
console.log('count in Nav Component :: '+this.count);
}
}
NavComponent HTML :
<a class="nav-link">Cart ( <i class="fa fa-shopping-cart"> {{count}} </i> )</a>
The count in NavComponent HTML is always showing 0. Please help
This is because you are re-providing the CartService in ProductListComponent... hence getting a different instance than the global one. Just remove it from the providers in ProductListComponent and it works.
BTW : you can check the docs for the injector tree, and as you are working with observables, you should also check the ChangeDetection strategies (OnPush would be better in your case). Also using something like :
// in nav.component.ts
count$: Observable<number>
...
this.count$ = this._cartService.currentCount
...
// in nav.component.html
...
{{count$ | async}}
...
```
would be more idiomatic and handle unsubscribing and change detection for you.