How to use service in angular


A service in angular has special duties such as fetching and pushing data from the server and to the server. The service can be used by any components.

Generate service

With following post you can quickly generate a service file which has special naming convention in Angularjs.

http request

Our service using a httpclient module to fetch data from the server. We need to import the library in

  • app.module.ts
  • list.service.ts

app.module.ts

In app.module we need to import the HttpClieneModule and also need to add the component in imports. For simplicity I skipped the rest of the code

...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
 ....
  imports: [
    BrowserModule,  
    HttpClientModule
  ],
 ....
})
export class AppModule { }

list.Service.ts

In the service.ts file we need to import and inject the dependency in the constructor as follows

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
....
@Injectable({
  providedIn: 'root'
})

export class ListService {
 constructor(private _http: HttpClient) { }
  _url = 'http://localhost:3004/todo';  
  constructor(private _http: HttpClient) { }
   Post(model : Model){
   return    this._http.post<any>('http:\\apiurl',model)
}
  
}

In the service we created a function for Post data and make a call to POST API request.

Using the service in component

To use the service in a component we need to perform the following

  • Import the service
  • Add dependency in constructor
  • create a function handler
import { TodoService } from './todo.service';
....
export class AppComponent {
 
  data = new Model('title', 'some text');
  constructor(private _service: TodoService) { }
  eventHandler(): void {
    this._service.Post(this.data).subscribe((data: any) => console.log('Success', data), (error: any) => console.log('Error', error) );
  }

To get the response we have to subscribe to the service. A service example project is available on the source code page.

Don’t forget to visit the source code page

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.