banner



How To Register A Service In Angularjs

Now that nosotros learned how data was shared among classes earlier services and that this wasn't very Dry out or scalable, let'south learn how to utilise services for dependency injection.

This is the second piece of a two-office commodity near dependency injection. In the first, we learned why we would want to use services in Athwart. In this post, we will look at how to utilise them.

Prerequisites

To be able to follow through in this article'southward demonstration, you should have:

  • An integrated development environment like VS Lawmaking
  • Node version 11.0 installed on your machine
  • Node Bundle Managing director version 6.7 (it usually ships with Node installation)
  • Athwart CLI version eight.0 or above
  • The latest version of Athwart (version 12)
          // run the command in a terminal ng version                  

Confirm that you are using version 12, and update to 12 if you are not.

  • Create a new Angular app with the command below:
          ng new serviceapp cd serviceapp                  

Other nice-to-haves include:

  • Working noesis of the Angular framework at a beginner level

Before Services Were Built-in

In the beginning part of this dependency injection serial, nosotros made a strong case for the use of services in our Angular applications. Benefits like writing modular code, efficiency and not having to repeat ourselves among other things make this a dandy arroyo. Make sure to read the first part of the post here.

Introduction to Services

Just put, services in Angular let you ascertain code or functionalities that are then accessible and reusable in many other components in your Angular project. Services help you with the brainchild of logic and data that is hosted independently just tin exist shared beyond other components.

The service class has a unmarried, well-defined function, helping you make your application construction very modular. It is different from other classes in Angular considering of the injection process. Dependency injection is the concept that makes it possible for you to receive dependencies from 1 class to another.

How Nosotros Will Be Using a Service

One of the biggest use cases for Angular services is managing or manipulating or even storing data. We will encounter how to create a service, register it and share information between two components today.

What We Are Building

We are going to re-create the application that displays artist information and locations like it is in the starting time part of the dependency injection series, but this fourth dimension effectually, we will utilise a service.

'Hi, this is the serviceapp' page with  'This is the list of Top African Music Artists' bulleted list: Davido who is currently number 1; Burna Boy who is currently number 2, etc. through number 5. A second list with header  'This is the location list of Top African Music Artists' includes bulleted list: Our number 1 artist in Africa is from Nigeria; Our number 2 artist in Africa is from Nigeria. etc. through number 5.

Getting Started

Open up your new app which you created at the get-go of this post, and in the terminal inside your VS Lawmaking (or any other IDE) generate the two components:

          ng generate component Artists ng generate component Artistnames                  

Navigate into the artist component and alter the content to the code blocks below:

                      // re-create inside component.ts file            import            {            Component,            OnInit            }            from            '@angular/core'            ;            @Component            (            {            selector:            'app-artists'            ,            templateUrl:            './artists.component.html'            ,            styleUrls:            [            './artists.component.css'            ]            }            )            export            form            ArtistsComponent            implements            OnInit            {            public            artists            =            [            {            'course'            :            one            ,            'proper name'            :            'Davido'            ,            'state'            :            'Nigeria'            }            ,            {            'grade'            :            2            ,            'name'            :            'Burna Boy'            ,            'country'            :            'Nigeria'            }            ,            {            'course'            :            three            ,            'name'            :            'Diamondz Platinum'            ,            'land'            :            'Tanzania'            }            ,            {            'grade'            :            4            ,            'name'            :            'Sarkodie'            ,            'country'            :            'Republic of ghana'            }            ,            {            'grade'            :            5            ,            'name'            :            'Mr. Eazi'            ,            'country'            :            'Nigeria'            }            ]            constructor            (            )            {            }            ngOnInit            (            )            :            void            {            }            }                  
                      <!-- re-create into component.html file -->                                          <h2              >                        This is the list of Top African Music Artists                                          </h2              >                                                      <ul              *ngFor                              =                "let artist of artists"                            >                                                      <li              >                        {{artist.name}} who is currently number {{artist.course}}                                          </li              >                                                      </ul              >                              

Now, in the second component, supersede the content with the lawmaking blocks below:

                      // re-create inside artistsname component.ts file            import            {            Component,            OnInit            }            from            '@athwart/core'            ;            @Component            (            {            selector:            'app-artistnames'            ,            templateUrl:            './artistnames.component.html'            ,            styleUrls:            [            './artistnames.component.css'            ]            }            )            export            course            ArtistnamesComponent            implements            OnInit            {            public            artists            =            [            {            'form'            :            1            ,            'name'            :            'Davido'            ,            'country'            :            'Nigeria'            }            ,            {            'grade'            :            2            ,            'proper name'            :            'Burna Boy'            ,            'land'            :            'Nigeria'            }            ,            {            'course'            :            iii            ,            'name'            :            'Diamondz Platinum'            ,            'land'            :            'Tanzania'            }            ,            {            'grade'            :            4            ,            'proper noun'            :            'Sarkodie'            ,            'country'            :            'Republic of ghana'            }            ,            {            'form'            :            5            ,            'name'            :            'Mr. Eazi'            ,            'country'            :            'Nigeria'            }            ]            constructor            (            )            {            }            ngOnInit            (            )            :            void            {            }            }                  
                      <!-- re-create into artistsname component.html file -->                                          <h2              >                        This is the location list of Tiptop African Music Artists                                          </h2              >                                                      <ul              *ngFor                              =                "let artist of artists"                            >                                                      <li              >                        Our number {{artist.grade}} artist in Africa is from {{artist.land}}                                          </li              >                                                      </ul              >                              

Finally, in the app component HTML file, supercede the content with the code block:

                                                    <div              >                                                      <h2              >                        How-do-you-do, this is the {{championship}}                                          </h2              >                                                      </div              >                                                      <app-artists              >                                                      </app-artists              >                                                      <app-artistnames              >                                                      </app-artistnames              >                              

If y'all save all files and run the application in development like this:

          ng serve                  

Y'all will see information technology looks exactly like what we have in the picture at the first of this section.

The job now is to have the data we have repeated in both components within a service from where it tin can be referenced someday it is needed.

Creating the Service

To create a service in Angular, you demand to run the generate service control:

          ng generate service data                  

Two new files will be created. Navigate to the data service.ts file, and make sure the content is the same as this:

                      import            {            Injectable            }            from            '@angular/core'            ;            @Injectable            (            {            providedIn:            'root'            }            )            export            grade            DataService            {            constructor            (            )            {            }            getList            (            )            {            render            [            {            'grade'            :            i            ,            'name'            :            'Davido'            ,            'state'            :            'Nigeria'            }            ,            {            'grade'            :            2            ,            'name'            :            'Burna Male child'            ,            'land'            :            'Nigeria'            }            ,            {            'course'            :            3            ,            'proper noun'            :            'Diamondz Platinum'            ,            'country'            :            'Tanzania'            }            ,            {            'grade'            :            4            ,            'name'            :            'Sarkodie'            ,            'country'            :            'Ghana'            }            ,            {            'grade'            :            5            ,            'name'            :            'Mr. Eazi'            ,            'land'            :            'Nigeria'            }            ]            ;            }            }                  

This data service has now been created and hard-coded information stored in the getList office.

Registration of Angular Service

At this phase, Angular takes this service as any other Angular class, and then to make sure Angular counts information technology every bit a service, we have to annals information technology. Information technology is as well of import to note the hierarchical style Angular handles things like dependency injection. Anywhere you register your service, dependencies can only exist injected into the said component or the child nodes. Then for our case, we are going to annals it at the root module.

Navigate to your app module file and make certain it looks like this:

                      import            {            BrowserModule            }            from            '@angular/platform-browser'            ;            import            {            NgModule            }            from            '@angular/core'            ;            import            {            AppComponent            }            from            './app.component'            ;            import            {            ArtistsComponent            }            from            './artists/artists.component'            ;            import            {            ArtistnamesComponent            }            from            './artistnames/artistnames.component'            ;            import            {            DataService            }            from            './data.service'            @NgModule            (            {            declarations:            [            AppComponent,            ArtistsComponent,            ArtistnamesComponent            ]            ,            imports:            [            BrowserModule            ]            ,            providers:            [DataService]            ,            bootstrap:            [AppComponent]            }            )            export            class            AppModule            {            }                  

Using the Service

To use the service we have fix in our projection, all we need to do is to import it where needed and bring functions from information technology through the component'southward constructor.

In your artist component, copy this code cake below into information technology:

                      import            {            Component,            OnInit            }            from            '@angular/core'            ;            import            {            DataService            }            from            '../data.service'            ;            @Component            (            {            selector:            'app-artists'            ,            templateUrl:            './artists.component.html'            ,            styleUrls:            [            './artists.component.css'            ]            }            )            export            class            ArtistsComponent            implements            OnInit            {            public            artists            =            [            ]            constructor            (            individual            list:            DataService)            {            }            ngOnInit            (            )            :            void            {            this            .artists            =            this            .list.            getList            (            )            ;            }            }                  

Yous can run across how this is washed and now we accept access to the functions alleged inside of the service we created.

Exercise the same for the Artistnames component:

                      import            {            Component,            OnInit            }            from            '@angular/core'            ;            import            {            DataService            }            from            '../data.service'            ;            @Component            (            {            selector:            'app-artists'            ,            templateUrl:            './artistname.component.html'            ,            styleUrls:            [            './artistname.component.css'            ]            }            )            consign            class            ArtistnameComponent            implements            OnInit            {            public            artists            =            [            ]            constructor            (            individual            list:            DataService)            {            }            ngOnInit            (            )            :            void            {            this            .artists            =            this            .list.            getList            (            )            ;            }            }                  

If you save all the files and refresh your browser, y'all volition see that the display is exactly the aforementioned every bit before:

Same image as before, the  'Hi, this is the serviceapp' page with  'This is the list of Top African Music Artists' and  'This is the location list of Top African Music Artists'.

This time, though, it is more efficient and very modular as nosotros have abstracted the role of data direction to a information service and at present components can serve their purposes without a need to repeat lawmaking or do more than they were congenital to do.

Conclusion

This has been a cracking introduction to using services in Angular. Nosotros looked at how we overburdened components in the past and how Angular has extensive features that help us encapsulate some things, thereby making the structures nosotros build more efficient and modular. Happy hacking!

How To Register A Service In Angularjs,

Source: https://www.telerik.com/blogs/angular-basics-how-to-use-services-angular

Posted by: youngmolaing58.blogspot.com

0 Response to "How To Register A Service In Angularjs"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel