Mellville
Mellville

Reputation: 1097

Observable: What's the difference between subscribing data in a component and in a service?

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?

Upvotes: 8

Views: 5327

Answers (4)

Aakash Garg
Aakash Garg

Reputation: 10979

Where to subscribe differs from architecture to architecture, or the problem you are trying to solve. Many applications store their data in ngrx store and subscribe to store's reducer for getting the data. In this case service will subscribe to http call and dispatch the data in store. Component will get data from store.

Lets say, you have 4 components in a view all showing list of countries. If one of them re fetch list of countries, you want all 4 to have the updated response. What you will do? you will subscribe to http call in service and put the data in your behavior subject or subject.

If you want to subscribe it in template, you can't subscribe it in service until you are subscribing the behavior subject's observable to which you will push the data.

If you are not using state management via ngrx or behavior subject or any other state sharing thing, you can then subscribe in component.

In case of non continuous observables like http calls unsubscribing is not required, its mainly required in continuous observable like if you are having an observable on a event.

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58593

You can write service anyhwere you want , but it depends on some standard way and requirements

Just like MVC architecture , where you can do all the thing on same page but you still do it in different module , just to make it more readable and make it reliable

This is the same thing with Angular2.

By writing the service in different file , you can make that service global or shareable by multiple component , that you can't do if you are writing in component.

If you want my opinion , make separate file for service and always write your code in it , no matter if it has only one service ( api / function ) , but in future when application gets bigger , you will see the benefits then.

Always subscribe from the component and never from the service

For More Detail : Please Read

Upvotes: 1

karthikaruna
karthikaruna

Reputation: 3246

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?

Upvotes: 1

JoshSommer
JoshSommer

Reputation: 2618

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.

Upvotes: 8

Related Questions