I wrote a function to check if a div should be displayed, like this :
shouldShowDiscount() {
console.log('shouldShowDiscount');
return this.baseSiteService.getActive().pipe(
switchMap(
(bucode, index) => {
console.log('bucode', bucode);
if (bucode == 'wtcph') {
return this.cartService.getActive().pipe(
tap(cart => {
console.log('cart', cart);
(cart?.customerGroupDiscountType == 'SC'
|| cart?.customerGroupDiscountType == 'PWD')
? this.hostClass.push('')
: this.hostClass.push('hide');
}
)
)
}
}
)
);
}
I put the function in ngOnInit :
ngOnInit() {
this.shouldShowDiscount();
}
However only the first console.log() before the return runs, the logs inside the operators won't run.
if I change the function call and add .subscribe()
then the console.logs will all run :
ngOnInit() {
this.shouldShowDiscount().subscribe(res => {
console.log(res)
});
}
is there a way to get it to work without the subscribe
?
CodePudding user response:
Maybe you should have a look at Observables. The idea is that they emit values, but only when there is a Observer to watch them. With subscribe you trigger that. Without calling subscribe to an Observable, he’ll never emit any value.
Note: be aware of the fact that every time you subscribe to an observable you have to close that subscription at some point, otherwise you’ll have memory leak.