ionic2Using Services


Remarks

One very important thing about using shared services, is that they must be included in the providers array of the top-most component where they must be shared.

Why is that? Well, Let's suppose that we include the MyService reference in the providers array from each Component. Something like:

@Component({
  templateUrl:"page1.html",
  providers: [MyService]
})

And

@Component({
  templateUrl:"page2.html",
  providers: [MyService]
})

That way a new instance of the service will be created for each component so the instance where one page will save the data, will be different from the instance used to get the data. So that won't work.

In order to make the entire app use the same instance (making the service work as a singleton service) we can add its reference in the App Component like this:

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [MyService]
})

You could also add the MyService reference in the ionicBootstrap(MyApp, [MyService]); but according Angular2 style guides

Do provide services to the Angular 2 injector at the top-most component where they will be shared.

Why? The Angular 2 injector is hierarchical.

Why? When providing the service to a top level component, that instance is shared and available to all child components of that top level component.

Why? This is ideal when a service is sharing methods or state.

Why? This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance.

And

It will work. It's just not a best practice. The bootstrap provider option is intended for configuring and overriding Angular's own preregistered services, such as its routing support.

... the App Component would be the best choice.