The difference between service and provider?
Provider and service are the same things. If we want a single instance of a service then we should create it as a provider. If we want to use dependency injection (injecting things through the constructor) we need to add the @Injectable decorator and add it to the provider’s array. If we are just creating a simple class that you just want to create new instances of then we don’t need to add it as a provider (we would just instantiate a new instance of it, i.e. let myThing = new Thing();
Most of the apps have a lot of communication between different pages. In this example, we are creating service provider which had already had default dummy data and we can change the data in page1 and change data can be display in a different page, We will display the service data / edited service data in page2.
In this example, we will learn
1. Sharing service provider data across multiple pages.
2. Detecting changes using getters and setters inside the service provider.
Service can be access by from all the component, all the external request should be in service and can return observable and HttP module are always with service guessing.
Step 1: ionic start SharedService blank –v2, profile page we have default vale of name and age field from the service provider user.ts. Clicking on GoToPage2 will take our service data to confirm page.
Step 2 Remove the existing home page and create two more page as page1 and page2. Add the following code in page1.html
Step 3: Add the following code in page1.ts
Step 5: Add the following code in page2.ts
Step 5: Create provide, syntax for creating provider ionic
>>ionic g provider provider-name-here
Create folder services in the src directory and provider file user.ts. We need to import @Injectable decorator so that we can be shared our service to different page and component. When we use the get/set method to do additional processing when other pages access or set the variables in this common class. or Add the following code in user.ts
We have to import our service provider in app.module.ts. Add the UserService in provider as
Once we inject provider in app.module, then we don’t need to reinject the dependency in other pages, we can use our common provider in other pages.