I know this is posted all over SO and the internet but I'm reading so many different things, I'm just a little confused now.
2 QUESTIONS -
- Where is the best place to subscribe to my component, the constructor(), or in NgOnInit()?
- Should I use a pipe when subscribing to an Observable so that Angular can destroy it or so I don't have to use ngondestroy? A little confused as to why there are pipes after subscribing?
Here is an example of one of my services where, in my navbar component, I subscribe to listening to a window size change coming from a service.
In my constructor, I have this -
this.responsiveService.getMobileStatus()
.subscribe(mobileStatus => {
this.isMobile = mobileStatus.status;
if (mobileStatus.width < 568) {
this.inputPlaceholder = this.placeholderWithSearch;
} else {
this.inputPlaceholder = this.placeholderWithoutSearch;
}
});
I would say better to use an
async
pipe and let angular handle the unsubscribing. It produces cleaner code;lets consider the code where the subscribing is in the constructor
With an
async
pipe we can refactorThe code is much shorter and also easier to test