Is there any significant difference between subscribing an observable in a component, or subscribing it in the service with a callback as a parameter?
Component
constructor(public dataService: DataService) {
this.dataService.getData()
.subscribe(users => {
this.user = users;
console.log(this.user);
});
Service
getData() {
return this.http.get(this.url)
.map(res => res.json())
}
VS
Component
constructor(public dataService: DataService) {
this.dataService.getData( callback => {
this.user = this.dataService.user;
});
Service:
getData(callback: (receiver: User) => void) {
return this.http.get(this.url)
.map(res => res.json())
.subscribe(users => {
this.user = users;
callback(this.user);
console.log(this.user);
});
}
The result is identical, so I don't quite get the difference, besides a bit more complex sintax. Which is the best aproach?
From my understanding, It's not considered a best practice to subscribe in a service. When you subscribe to an observable (particularly a hot observable, since they don't complete) it creates a subscription. If you do not unsubscribe from the subscriptions, with the Async pipe or manually, then it can create memory leaks that will degrade your application's performance. But hiding the subscription also prevents the observable from being chained to other observables to create more "reactive" applications.
In your example above example, I would never have that subscribes in the service and sets a public property for angular to watch. Also, it could potentially lead to change detection issues along with other issues including maintainability.
It's just an architectural style. The best approach is to subscribe from the component, as you sometimes may face a scenario to do something with your component's members as the service returns.
For instance, you may want to close a modal that's a part of the component, as the service returns.
If you subscribe in the service, you'll not have access to the modal, which is a part of the component, unless you pass a reference explicitly, which obviously is not an elegant way.
If you subscribe in the component, you can do anything, you can do anything with the component's members, before / after doing something with the data.
Also, a good analogy would be, subscribing to a food delivery service.
Which option would you prefer?
Give your number to the restaurant and ask them to call you as soon as the food is ready, or getting delivered it at your door as the food becomes ready?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With