banner



What Is A Provider Ionic 2 What Is A Provider Versus Service In Ionic 2

Injectables, Services, Providers whatever you lot call them (I like to call them services), they are a critical part of building applications with Ionic 2. Components are the courage of our applications, they are responsible for what we actually encounter on the screen, but services play an important office in providing data to our application and performing tasks for u.s..

To requite you lot an idea of the types of things you lot might practise of services, here's some of the services I take built into my Ionic 2 applications:

  • ConnectivityMonitor this allows me to easily bank check whether a device is online or offline
  • SimpleAlert a service that allows me to display uncomplicated alerts with one line of code
  • Data I use data services all the time, they provide the information the application needs to role, without the app having to worry near how that data is fetched (it could be stored locally, or it could exist retrieved from a server). If I have multiple types of information in an app I may even create multiple Data providers, i.e: PostData, UserData and and so on
  • GoogleMaps This one handles setting up the Google Maps SDK in an awarding so all I need to practise in my components is phone call a single function
  • Dropbox This service handles interfacing with the Dropbox API
  • and many more

This tutorial isn't going to focus on how to build specific services, just rather how they work and how to employ them in general. We are likewise going to encompass an important distinction between ii dissimilar methods of adding them to your applications, and how that can drastically effect how they function.

How to Apply a Service

When using a service that you lot take created (we will get to the actually creating it office a petty later), in that location's a couple of of import concepts to understand. In order to use a service you need to import it, add a provider for it, and you also need to inject it. The service needs to be imported into any class that uses it, like this:

                                                    import                                  {                                MyService                                  }                                from                                                './path/to/service'                ;                                            

and it tin can exist injected into the constructor similar this:

                                                    constructor                (                individual                                                myService                :                                MyService                ){                                                                                                          }                                            

which will create a member variable called myService that tin be accessed anywhere within the grade through this.myService. The simply thing left to do is add a provider for it, which can be done in ane of two means. It can be added to an individual component like this:

                                                    @                Component                ({                                                                                                    template:                                                `<p>Hey!</p>`                ,                                                                                                    providers:                                  [                MyService                ]                                                                    })                                            

or it tin be added globally to the application when bootstrapping in the root component (app.ts):

                                                    ionicBootstrap                (                MyApp                , [                MyService                ]);                                            

Which of these 2 you lot cull tin can thing a corking deal. If you lot add together it to the bootstrap and then a unmarried case of the service will be created that all components in the application will share making it a great mode to share data between components. If you add together the provider to an individual component, then a new instance will be created for merely that one component.

Providers in Ionic 2

Remember that a grade is simply a blueprint for an object you want to create. So we can create multiple copies of the same service, all of which operate completely independent of each other. In the case above the service is being provided in the root component (significant it is added to the ionicBootstrap role) so that makes that instance of the service available throughout the entire application. This means that Tab 2 tin can admission information technology without declaring its own provider (as could Tab Three and Tab Four if they exists), but, the service still needs to be imported.

Tab One in the example above likewise has its own provider (significant the service is alleged inside that components decorator), which means it is creating its ain case of the service. The stop event is a single service beingness shared by the entire application, except for Tab One which has gone and created its own re-create of the service.

It'south important to understand the departure betwixt these approaches. Suppose you lot had created a service to store some data and share it betwixt pages in your application. If you lot provide the service through ionicBootstrap then everything volition work great, considering the entire app is sharing the same instance of the service. Only if you were to provide the service in each component individually, they would all have their own instances of the service if one page saved some information to the service, and you tried to admission it from another page it wouldn't piece of work.

Once yous get your caput around it all seems pretty straightforward, simply I recollect it can exist pretty confusing. I'k going to run through a simple example which should illustrate the signal pretty well.

Before we Get Started

Before you go through this tutorial, you lot should have at least a basic understanding of Ionic ii concepts. You lot must too already have Ionic two set up on your machine.

If yous're not familiar with Ionic 2 already, I'd recommend reading my Ionic 2 Beginners Guide first to go up and running and understand the bones concepts. If you want a much more than detailed guide for learning Ionic two, then take a look at Building Mobile Apps with Ionic ii.

Generate a New Ionic 2 Awarding

Let's commencement off by creating a new awarding

Generate a new application by running the post-obit command:

                                    ionic showtime ionic2-providers blank --v2                              

We are likewise going to run a few more commands to generate a test service for the states to use, and a couple of pages that nosotros will apply as tabs to demonstrate some differences in the two approaches.

Run the following commands:

                                    ionic k folio TestProvider                              
                                    ionic m folio PageOne                              
                                    ionic g page PageTwo                              

Since nosotros want to employ a tab structure so that we can easily switch between these two pages, we are going to accept to exercise a bit more work to set it up.

Modify abode.ts to reverberate the following:

                                                    import                                  {                Component                }                                from                                                '@angular/core'                ;                                                                    import                                  {                NavController                }                                from                                                'ionic-athwart'                ;                                                                    import                                  {                PageOnePage                }                                from                                                '../page-1/page-1'                ;                                                                    import                                  {                PageTwoPage                }                                from                                                '../page-ii/page-two'                ;                                                                                                          @                Component                ({                                                                                                    templateUrl:                                                'build/pages/home/domicile.html'                                                                    })                                                                    export                                                class                                                HomePage                                  {                                                                                                                                          tab1Root                :                                whatever                                  =                                PageOnePage                ;                                                                                                    tab2Root                :                                any                                  =                                PageTwoPage                ;                                                                                                                                          constructor                (                private                                                navController                :                                NavController                ) {                                                                                                                            }                                                                    }                                            

Modify domicile.html to reflect the following:

                                                    <                ion-tabs                >                                                                                                    <                ion-tab                                                [root]                =                "tab1Root"                                                tabTitle                =                "Page ane"                ></                ion-tab                >                                                                                                    <                ion-tab                                                [root]                =                "tab2Root"                                                tabTitle                =                "Page 2"                ></                ion-tab                >                                                                    </                ion-tabs                >                                            

Now we have imported our ii pages and set them upward as tabs. If y'all load upwards the application now yous should be able to switch between the ii tabs.

Create the Service

The service we create for this sit-in is going to be very elementary. All it volition allow u.s.a. to do is set a unmarried message, which we can and so recollect and display later

If you take a look at the TestProvider we generated with the command line earlier, information technology volition wait similar this:

                                                    import                                  {                                Injectable                                  }                                from                                                '@angular/core'                ;                                                                    import                                  {                                Http                                  }                                from                                                '@athwart/http'                ;                                                                    import                                                'rxjs/add/operator/map'                ;                                                                                                          @                Injectable                ()                                                                    export                                                class                                                TestProvider                                  {                                                                                                    data                :                                any                ;                                                                                                                                          constructor                (                private                                                http                :                                Http                ) {                                                                                                    this                .                information                                  =                                null                ;                                                                                      }                                                                                                                                          load                () {                                                                                                    if                                  (                this                .                data                ) {                                                                                                    return                                                Promise                .                resolve                (                this                .                data                );                                                                                      }                                                                                                                                          return                                                new                                                Promise                (                resolve                                                =>                                  {                                                                                                    this                .                http                .                get                (                'path/to/information.json'                )                                                                                      .                map                (                res                                                =>                                                res                .                json                ())                                                                                      .                subscribe                (                data                                                =>                                  {                                                                                                    this                .                data                                  =                                information                ;                                                                                                    resolve                (                this                .                data                );                                                                                      });                                                                                      });                                                                                      }                                                                    }                                            

This is the default provider that Ionic generates (except I have removed the comments for brevity). It contains some dummy code that fetches some data from a hypothetical JSON file. We are going to modify this to make information technology a lot simpler.

Modify test-provider.ts to reflect the following:

                                                    import                                  {                                Injectable                                  }                                from                                                '@athwart/core'                ;                                                                                                          @                Injectable                ()                                                                    export                                                course                                                TestProvider                                  {                                                                                                                                          public                                                bulletin                :                                whatsoever                                  =                                "I'm new here"                ;                                                                                                                                          constructor                () {                                                                                                                            }                                                                                                                                          setMessage                (                message                ) {                                                                                                    this                .                bulletin                                  =                                message                ;                                                                                      }                                                                    }                                            

Much simpler. Now we tin fix a message past using the setMessage function, and since the bulletin member variable is publicly exposed nosotros will be able to admission that direct.

Set up the Service

Now that we have our service, we need to import information technology, provide it, and inject it, before we tin can use it. As I mentioned, we can provide the service either through the ionicBootstrap function in the root component, or through the component itself both of these will accept different effects.

Nosotros are going to start off by calculation it to ionicBootstrap which will create a unmarried instance of the service for the entire application.

Modify app.ts to reflect the following:

                                                    import                                  {                                Component                                  }                                from                                                '@athwart/cadre'                ;                                                                    import                                  {                                Platform                ,                                ionicBootstrap                                  }                                from                                                'ionic-athwart'                ;                                                                    import                                  {                                StatusBar                                  }                                from                                                'ionic-native'                ;                                                                    import                                  {                                HomePage                                  }                                from                                                './pages/home/home'                ;                                                                    import                                  {                                TestProvider                                  }                                from                                                './providers/test-provider/test-provider'                ;                                                                                                          @                Component                ({                                                                                                    template:                                                '<ion-nav [root]="rootPage"></ion-nav>'                ,                                                                    })                                                                    export                                                grade                                                MyApp                                  {                                                                                                    rootPage                :                                whatever                                  =                                HomePage                ;                                                                                                                                          constructor                (                platform                :                                Platform                ) {                                                                                                    platform                .                ready                ().                and so                (()                                =>                                  {                                                                                                    StatusBar                .                styleDefault                ();                                                                                      });                                                                                      }                                                                    }                                                                                                          ionicBootstrap                (                MyApp                , [                TestProvider                ]);                                            

Now we are going to take to gear up our two pages then that they can also make utilise of the service.

Modify folio-one.html to reverberate the post-obit:

                                                    <                ion-header                >                                                                                                    <                ion-navbar                >                                                                                                    <                ion-title                >                Page I                </                ion-title                >                                                                                                    <                ion-buttons                                                end                >                                                                                                    <                push button                                                primary                                                (click)                =                "changeMessage()"                >                                                                                                    <                ion-icon                                                name                =                "newspaper"                ></                ion-icon                >                                                                                                    </                button                >                                                                                                    </                ion-buttons                >                                                                                                    </                ion-navbar                >                                                                    </                ion-header                >                                                                                                          <                ion-content                                                padding                >                                                                                                    <                h2                >                {{testProvider.message}}                </                h2                >                                                                    </                ion-content                >                                            

In the template nosotros are simply displaying the message that nosotros are accessing through the service (which we will set up in the class for this component in a moment). We also add together a button to the header that when clicked will call the changeMessage function this is what we will use to modify the message in the service.

Alter page-i.ts to reverberate the following:

                                                    import                                  {                                Component                                  }                                from                                                '@angular/cadre'                ;                                                                    import                                  {                                NavController                                  }                                from                                                'ionic-angular'                ;                                                                    import                                  {                                TestProvider                                  }                                from                                                '../../providers/test-provider/test-provider'                ;                                                                                                          @                Component                ({                                                                                                    templateUrl:                                                'build/pages/folio-one/page-ane.html'                ,                                                                    })                                                                    consign                                                class                                                PageOnePage                                  {                                                                                                                                          constructor                (                private                                                nav                :                                NavController                ,                                individual                                                testProvider                :                                TestProvider                ) {                                                                                                                            }                                                                                                                                          changeMessage                (){                                                                                                    this                .                testProvider                .                setMessage                (                "Page one rocks!"                );                                                                                      }                                                                                                          }                                            

In this class we are importing the service, and then we inject information technology into the constructor which makes it bachelor to use throughout the class. Since we accept already provided it in the root component, we have everything gear up up that we demand to use the service. Nosotros have also gear up the changeMessage office to alter the message stored in the service to "Page 1 rocks!".

Now permit'south do the same matter for page two.

Modify page-ii.html to reflect the post-obit:

                                                    <                ion-header                >                                                                                                    <                ion-navbar                >                                                                                                    <                ion-title                >                Folio Ii                </                ion-title                >                                                                                                    <                ion-buttons                                                end                >                                                                                                    <                button                                                primary                                                (click)                =                "changeMessage()"                >                                                                                                    <                ion-icon                                                name                =                "paper"                ></                ion-icon                >                                                                                                    </                push button                >                                                                                                    </                ion-buttons                >                                                                                                    </                ion-navbar                >                                                                    </                ion-header                >                                                                                                          <                ion-content                                                padding                >                                                                                                    <                h2                >                {{testProvider.message}}                </                h2                >                                                                    </                ion-content                >                                            

Change page-two.ts to reverberate the following:

                                                    import                                  {                                Component                                  }                                from                                                '@angular/core'                ;                                                                    import                                  {                                NavController                                  }                                from                                                'ionic-athwart'                ;                                                                    import                                  {                                TestProvider                                  }                                from                                                '../../providers/test-provider/test-provider'                ;                                                                                                          @                Component                ({                                                                                                    templateUrl:                                                'build/pages/page-two/page-two.html'                                                                    })                                                                    export                                                class                                                PageTwoPage                                  {                                                                                                                                          constructor                (                individual                                                nav                :                                NavController                ,                                private                                                testProvider                :                                TestProvider                ) {                                                                                                                            }                                                                                                                                          changeMessage                (){                                                                                                    this                .                testProvider                .                setMessage                (                "Page two rocks!"                );                                                                                      }                                                                                                          }                                            

We've washed exactly the same matter for page two, except that its changeMessage office will modify the message to "Page two rocks!" instead.

In both of the pages nosotros are importing the TestProvider but, and this is the of import part, we are not declaring information technology as a provider in the decorator. This means that both of the pages volition use the example of TestProvider that was created in the root component, meaning if nosotros modify the message in one page, then it will consequence the other.

Give it a try, initially both tabs should say "I'm new here". If you click the push button on the first tab both tabs will modify to "Folio one rocks!", and if you click the button on the 2nd tab both tabs will change to "Page two rocks!".

Now let'south run into what happens when they create their own instance of the provider.

Modify page-1.ts to reflect the post-obit:

                                                    import                                  {                                Component                                  }                                from                                                '@angular/core'                ;                                                                    import                                  {                                NavController                                  }                                from                                                'ionic-angular'                ;                                                                    import                                  {                                TestProvider                                  }                                from                                                '../../providers/test-provider/exam-provider'                ;                                                                                                          @                Component                ({                                                                                                    templateUrl:                                                'build/pages/folio-i/page-one.html'                ,                                                                                                    providers:                                  [                TestProvider                ]                                                                    })                                                                    export                                                class                                                PageOnePage                                  {                                                                                                                                          constructor                (                private                                                nav                :                                NavController                ,                                private                                                testProvider                :                                TestProvider                ) {                                                                                                                            }                                                                                                                                          changeMessage                (){                                                                                                    this                .                testProvider                .                setMessage                (                "Page one rocks!"                );                                                                                      }                                                                                                          }                                            

Alter page-two.ts to reflect the following:

                                                    import                                  {                                Component                                  }                                from                                                '@angular/core'                ;                                                                    import                                  {                                NavController                                  }                                from                                                'ionic-angular'                ;                                                                    import                                  {                                TestProvider                                  }                                from                                                '../../providers/test-provider/test-provider'                ;                                                                                                          @                Component                ({                                                                                                    templateUrl:                                                'build/pages/folio-2/page-two.html'                ,                                                                                                    providers:                                  [                TestProvider                ]                                                                    })                                                                    export                                                form                                                PageTwoPage                                  {                                                                                                                                          constructor                (                private                                                nav                :                                NavController                ,                                private                                                testProvider                :                                TestProvider                ) {                                                                                                                            }                                                                                                                                          changeMessage                (){                                                                                                    this                .                testProvider                .                setMessage                (                "Page ii rocks!"                );                                                                                      }                                                                                                          }                                            

As you tin see, we are at present adding a provider for TestProvider directly into each components decorator. Information technology is now no longer necessary to take the provider in ionicBootstrap, all the same keeping it there won't have any effect so it'southward not important to remove for this demonstration.

Now if yous click the push on ane tab, the message will only change for that ane tab. Each tab now has its own copy (instance) of the service, so when the changeMessage office is called, it only effects that components own instance of the service.

Summary

Depending on the circumstance, either method for providing a service in your application may exist desired, simply it'southward important to empathize the distinction between the two, otherwise you could find yourself running into some frustrating issues.

What Is A Provider Ionic 2 What Is A Provider Versus Service In Ionic 2,

Source: https://www.joshmorony.com/an-in-depth-explanation-of-providers-in-ionic-2/

Posted by: edgertonwasmand.blogspot.com

0 Response to "What Is A Provider Ionic 2 What Is A Provider Versus Service In Ionic 2"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel