banner



What Is A Provider Ionic 2 What Is The Difference Between Service And Provider Ionic 2

Injectables, Services, Providers whatever you phone call them (I similar to call them services), they are a critical function of building applications with Ionic 2. Components are the backbone of our applications, they are responsible for what nosotros really encounter on the screen, just services play an of import role in providing information to our application and performing tasks for us.

To give you an idea of the types of things you might practice of services, here's some of the services I accept congenital into my Ionic 2 applications:

  • ConnectivityMonitor this allows me to hands check whether a device is online or offline
  • SimpleAlert a service that allows me to display elementary alerts with one line of lawmaking
  • Information I apply information services all the fourth dimension, they provide the data the awarding needs to function, without the app having to worry most how that data is fetched (information technology could be stored locally, or information technology could be retrieved from a server). If I accept multiple types of information in an app I may fifty-fifty create multiple Data providers, i.eastward: PostData, UserData and so on
  • GoogleMaps This one handles setting upwardly the Google Maps SDK in an awarding then all I need to do in my components is call a single office
  • 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, but rather how they work and how to apply them in full general. We are too going to cover an important stardom between two different methods of adding them to your applications, and how that tin can drastically effect how they function.

How to Utilize a Service

When using a service that you take created (nosotros volition get to the really creating information technology part a little afterwards), in that location's a couple of important concepts to understand. In order to utilise a service y'all need to import information technology, add a provider for information technology, and you too need to inject it. The service needs to be imported into any grade that uses it, like this:

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

and it can be injected into the constructor like this:

                                                    constructor                (                private                                                myService                :                                MyService                ){                                                                                                          }                                            

which volition create a member variable chosen myService that tin can be accessed anywhere within the class through this.myService. The only matter left to do is add a provider for it, which can be done in one of two ways. It can be added to an individual component similar this:

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

or information technology tin be added globally to the awarding when bootstrapping in the root component (app.ts):

                                                    ionicBootstrap                (                MyApp                , [                MyService                ]);                                            

Which of these ii y'all choose can matter a great bargain. If you add together it to the bootstrap then a single instance of the service will be created that all components in the awarding will share making it a great way to share information betwixt components. If you add together the provider to an private component, then a new instance will exist created for just that one component.

Providers in Ionic 2

Remember that a class is but a blueprint for an object y'all desire to create. Then we tin create multiple copies of the same service, all of which operate completely contained of each other. In the example above the service is being provided in the root component (meaning it is added to the ionicBootstrap function) so that makes that instance of the service available throughout the entire awarding. This means that Tab Two tin access information technology without declaring its own provider (every bit could Tab Iii and Tab 4 if they exists), just, the service still needs to be imported.

Tab One in the example higher up also has its own provider (meaning the service is declared inside that components decorator), which ways it is creating its own instance of the service. The finish result is a unmarried service being shared by the unabridged awarding, except for Tab One which has gone and created its own copy of the service.

It'south important to sympathize the difference between these approaches. Suppose you had created a service to store some data and share information technology between pages in your awarding. If you provide the service through ionicBootstrap then everything will work cracking, because the entire app is sharing the same instance of the service. But if you lot were to provide the service in each component individually, they would all have their own instances of the service if i page saved some information to the service, and you lot tried to access information technology from another page it wouldn't work.

In one case y'all get your head around it all seems pretty straightforward, but I call up it tin be pretty confusing. I'thousand going to run through a simple instance which should illustrate the point pretty well.

Before we Get Started

Earlier you go through this tutorial, yous should accept at least a basic understanding of Ionic 2 concepts. You must too already have Ionic ii ready on your machine.

If you're not familiar with Ionic 2 already, I'd recommend reading my Ionic two Beginners Guide first to get upwardly and running and understand the basic concepts. If you desire a much more detailed guide for learning Ionic 2, then take a look at Building Mobile Apps with Ionic two.

Generate a New Ionic two Awarding

Let's starting time off by creating a new application

Generate a new awarding by running the following command:

                                    ionic start ionic2-providers blank --v2                              

Nosotros are also going to run a few more commands to generate a test service for us to use, and a couple of pages that we volition use as tabs to demonstrate some differences in the ii approaches.

Run the following commands:

                                    ionic yard page TestProvider                              
                                    ionic g page PageOne                              
                                    ionic g page PageTwo                              

Since we want to use a tab structure and then that we can easily switch between these two pages, we are going to have to do a chip more work to set it upwards.

Change home.ts to reverberate the following:

                                                    import                                  {                Component                }                                from                                                '@athwart/core'                ;                                                                    import                                  {                NavController                }                                from                                                'ionic-athwart'                ;                                                                    import                                  {                PageOnePage                }                                from                                                '../folio-one/page-one'                ;                                                                    import                                  {                PageTwoPage                }                                from                                                '../page-2/folio-two'                ;                                                                                                          @                Component                ({                                                                                                    templateUrl:                                                'build/pages/home/dwelling house.html'                                                                    })                                                                    export                                                grade                                                HomePage                                  {                                                                                                                                          tab1Root                :                                any                                  =                                PageOnePage                ;                                                                                                    tab2Root                :                                whatsoever                                  =                                PageTwoPage                ;                                                                                                                                          constructor                (                private                                                navController                :                                NavController                ) {                                                                                                                            }                                                                    }                                            

Modify habitation.html to reflect the post-obit:

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

At present we have imported our two pages and set them upwardly as tabs. If yous load up the application now yous should be able to switch betwixt the two tabs.

Create the Service

The service we create for this sit-in is going to be very elementary. All it will allow u.s. to do is ready a single message, which we tin can then retrieve and brandish after

If you accept a look at the TestProvider we generated with the command line earlier, it volition look like this:

                                                    import                                  {                                Injectable                                  }                                from                                                '@angular/core'                ;                                                                    import                                  {                                Http                                  }                                from                                                '@angular/http'                ;                                                                    import                                                'rxjs/add/operator/map'                ;                                                                                                          @                Injectable                ()                                                                    export                                                class                                                TestProvider                                  {                                                                                                    information                :                                any                ;                                                                                                                                          constructor                (                individual                                                http                :                                Http                ) {                                                                                                    this                .                data                                  =                                null                ;                                                                                      }                                                                                                                                          load                () {                                                                                                    if                                  (                this                .                data                ) {                                                                                                    return                                                Promise                .                resolve                (                this                .                data                );                                                                                      }                                                                                                                                          return                                                new                                                Promise                (                resolve                                                =>                                  {                                                                                                    this                .                http                .                become                (                'path/to/data.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 lawmaking that fetches some data from a hypothetical JSON file. We are going to modify this to brand it a lot simpler.

Modify examination-provider.ts to reverberate the following:

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

Much simpler. Now nosotros can set a message by using the setMessage function, and since the message member variable is publicly exposed we will exist able to access that directly.

Set up the Service

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

We are going to outset off past adding it to ionicBootstrap which will create a unmarried instance of the service for the entire application.

Alter app.ts to reflect the following:

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

At present we are going to take to set up up our 2 pages then that they can besides make use of the service.

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

                                                    <                ion-header                >                                                                                                    <                ion-navbar                >                                                                                                    <                ion-championship                >                Page One                </                ion-title                >                                                                                                    <                ion-buttons                                                end                >                                                                                                    <                button                                                chief                                                (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                >                                            

In the template nosotros are only displaying the message that we are accessing through the service (which we will set up in the grade for this component in a moment). Nosotros as well add a button to the header that when clicked will telephone call the changeMessage part this is what we will employ to change the message in the service.

Alter page-1.ts to reflect the following:

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

In this form we are importing the service, and then nosotros inject it into the constructor which makes it bachelor to use throughout the class. Since we accept already provided it in the root component, nosotros have everything set that we need to apply the service. We accept too set up up the changeMessage office to change the message stored in the service to "Page one rocks!".

Now permit's practise the same thing for page two.

Change page-ii.html to reflect the following:

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

Modify page-two.ts to reflect the following:

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

We've done exactly the aforementioned affair for page two, except that its changeMessage function will change the message to "Page two rocks!" instead.

In both of the pages nosotros are importing the TestProvider but, and this is the important function, nosotros are not declaring information technology as a provider in the decorator. This means that both of the pages volition use the instance of TestProvider that was created in the root component, significant if we modify the message in ane page, then it will upshot the other.

Requite it a endeavor, initially both tabs should say "I'1000 new here". If you click the button on the first tab both tabs will alter to "Page one rocks!", and if you click the button on the second tab both tabs will change to "Page two rocks!".

Now permit's see what happens when they create their own instance of the provider.

Modify page-one.ts to reflect the following:

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

Modify page-two.ts to reflect the following:

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

As you tin run into, we are now adding a provider for TestProvider directly into each components decorator. Information technology is now no longer necessary to have the provider in ionicBootstrap, however keeping it at that place won't accept any effect so information technology's not important to remove for this sit-in.

At present if you lot click the button on one tab, the message will but change for that i tab. Each tab at present has its own re-create (example) of the service, so when the changeMessage function is chosen, it simply furnishings that components own instance of the service.

Summary

Depending on the circumstance, either method for providing a service in your application may exist desired, but it's important to understand the distinction between the 2, otherwise you could notice yourself running into some frustrating issues.

What Is A Provider Ionic 2 What Is The Difference Between Service And Provider Ionic 2,

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

Posted by: owensrigand73.blogspot.com

0 Response to "What Is A Provider Ionic 2 What Is The Difference Between Service And Provider Ionic 2"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel