Web
Analytics
angular 4 services with example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

When we write the angular source code we usually need some data functions that would be shared across different components in an application. In that condition, we have to write same function code in different components that don’t make sense. In this scenario, we can develop some angular services which may be shared across different components.we also capable to share data across different components using Angular services. Angular services are the concept of dependency injection.
Angular services are task-based. Services are reusable code which shared among different components. Angular provides built-in(HTTP, router, animation, form, UI Library,) and custom services. services work on dependency injection mechanism.
Services may be written by just defining a typescript(with extension .service.ts) class with decorator @Injectable annotation. Providers are used to declaring or injecting classes, functions, and values by which they may be used by the dependency injection mechanism.
Services may be injected in different components, modules, and other services.

Let’s begin with an example.

Step 1: First we create service using angular cli. Write following angular cli command into integrated terminal

ng g service data

It will create two files named data.service.ts and data.service.spec.ts.

Step 2: Write the following code into service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  // Create array
  hobbies = [
    'dancing',
    'singing',
    'internet'
  ];
  constructor() { }
 // Create simple angular service method
  servicemethod(){
      return 'Its just a simple service method';
  }

}

In the above code block, an array “hobbies” and function “servicemethod” are defined which may be used by any components.

Step 3: Update app.module.ts (Pass the reference to newly created service and add providers)

// Import reference of service
import { DataService } from './data.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';


import { AppComponent } from './app.component';



@NgModule({
  declarations: [
    AppComponent,  
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  // Add provider
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have to pass newly created service class name into the provider of app.module.ts. After it this services may be injectable to other components.

<script async src=”//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>
<!– big size add for between blogs –>
<ins class=”adsbygoogle”
style=”display:inline-block;width:970px;height:250px”
data-ad-client=”ca-pub-9934076637261479″
data-ad-slot=”9062913449″></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Step4 : Update app.component.ts as following code

import { DataService } from './data.service';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <p>hi {{data}}</p>
  <li *ngFor="let h of itemsarray">
  <b> {{h}} </b>           
</li>
  `,
  styles: [`
 p
  {
    background-color:green;
  }

  `],
  // Don't forget to add reference of DataService
  providers:[DataService]
})
export class AppComponent {
  // String and array variable declartion
  data;
  itemsarray=[]
  constructor(private dataservice: DataService) {
    // use property of service
    this.itemsarray = this.dataservice.hobbies;
    // use method of service
    this.data = this.dataservice.servicemethod();
  }
 }

In above code our custom service instance “dataservice” is created and using this instance we are accessing the variable and function of angular custom service.

Step 5: Save and run using the following command

ng serve –open

Output:


Angular 5 Online Training

Angular 5 Online Training