Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any harm in binding directly to service properties?

Tags:

angular

Is there any harm in the approach of creating a service which holds some state of my angular application, injecting that service into the components that are conditioning on the state and then in their templates binding directly to the respective properties of that service?

I saw that frequently Subjects are used to trigger state updates across components and was wondering if there are any scenarios where the approach described above wouldn't work and one has to use Subjects instead.

like image 466
tobigue Avatar asked Feb 23 '18 17:02

tobigue


Video Answer


1 Answers

I often find that devs are not taking advantage of the binding and change detection available in Angular and basically circumventing it by using Subjects when they don't really need to.

For example, I have a complete Subject/Behavior subject example here: https://github.com/DeborahK/MovieHunter-communication in the MH-Take3 folder.

I then have the exact same functionality using simple properties in the MH-Take4 folder with no Subject/BehaviorSubject and quite a bit less code.

The one thing I would recommend, however, is to wrap your service property into a component property so that your template does not need to know about your service. This is not required, but provides good encapsulation.

For example:

get showImage(): boolean {
    return this.movieParameterService.displayPosters;
}
set showImage(value: boolean) {
    this.movieParameterService.displayPosters = value;
}

I have a "parameter" service that retains the parameters for one of my views. In this case, it is retaining whether the user has turned the display of images on or off. I expose the service parameter using a getter and setter in the component. That way the template binds to the component and does not need to know about the service.

In addition to the basic benefits of encapsulation, this also makes it easier to use editor features such as "Find all references" as it will find the components that use the service. It won't find any if the only reference is in strings in the template.

like image 123
DeborahK Avatar answered Oct 20 '22 12:10

DeborahK