1

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 ?

1
  • 1
    In short, no. Either you subscribe or some library subscribes on your behalf. Commented Aug 2, 2022 at 13:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.