Services

The preceding snippet contains static data that is binded to the phoneList property and thus rendered accordingly, which is a synchronous operation. Now, what if we need the asynchronous data to be displayed? Let's consume our phonebook APIs and create an HTTP service for our client so that we can display the asynchronous data. Let's create a service file called phonebook.service.ts. This file contains all the HTTP request methods required to get and set the data. For now, let's create a getContactlist method, which will get all the contact data present on the server. The required code is as follows:

import { Injectable } from '@Angular/core';
import { HttpClient } from '@Angular/common/http';
import 'rxjs/add/operator/map'
@Injectable()
export class PhonebookService {
constructor(private http: HttpClient) {}
getContactList() {
return this.http.get('http://localhost:8000/phone/list')
}
}

Here, we imported the HttpClient service for making XML HTTP requests from our browser. The Injectable function is needed to make this file a service provider. The metadata in the injectable is not provided as Angular itself will emit the metadata. Next, we will be using this service by injecting it inside the component's constructor. We have passed a parameterized value in the constructor, which is referred to as the dependency injection.

Modify the current code to the following code of list.components.ts:

import { Component } from '@Angular/core';
import { PhonebookService } from './phonebook.service';
@Component({
selector: 'list',
templateUrl: './list.component.html'
})
export class ListComponent {
public phoneList = []
constructor(private _pbService: PhonebookService) {
this._pbService.getContactList()
.subscribe((response) => {
this.phoneList = response['data'];
})
}
}

Finally, we need to register the service under the providers in app.modules, as we are using it across the app. At this step, we need to have the following code in app.modules:

import {HttpClientModule} from '@Angular/common/http';
import {PhonebookService} from './phonebook.service';

And include it in the providers list of ngModule:

@NgModule({
declarations: [
ListComponent,
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [PhonebookService],
bootstrap: [AppComponent]
})

For using the Httpclient service, we first need to register httpModule in NgModules.
Also, make sure our phonebook API node server is already running. If not, start it using npm start, and once we start ng serve --open, we will be receiving the list of superheroes contacts from the server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.34.39