0

While going through the documentation for NgBootstraps Table component, I noticed that they use getters and setters to access their Subjects from a service. See example here: https://ng-bootstrap.github.io/stackblitzes/table/complete/stackblitz.html in the country.service.ts

I have always just directly subscribed to services from my other components. ie rather than using a

 get countries$() { return this._countries$.asObservable(); }

I'd just read this._countryService._countries$, and subscribe to it or use async pipe as needed.

Is it a better practise to use getters and setters like this?

  • The main advantage I see here is that other components that are subscribing just see an `Observable` instead of a `Subject`, as they should not care that it is a `Subject`. In other words, this is just an example of encapsulation. – Chris Yungmann Feb 01 '21 at 19:06
  • Related: https://stackoverflow.com/q/61288259/9287029, https://stackoverflow.com/q/36986548/9287029, https://stackoverflow.com/questions/65121970/should-i-use-asobservable-in-behaviorsubject – Chris Yungmann Feb 01 '21 at 19:10
  • Is there a reason? Sure! Are there good reasons: debatable. Mostly I'd call it person style. And although I don't like his / her variable naming, its still the same thing: Personal choices and objectives more than anything concrete – Austin T French Feb 01 '21 at 19:14

0 Answers0