Angular 6 HTTP Client
Angular comes with a built in HTTPClient. Let's import that at the top of our data.service.ts file:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
Next, in order to use the HttpClient, we need to create an instance of it through dependency injection within the constructor: constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
We also defined a method called getUsers() which we'll call in our component shortly. It returns a list of users from a public testing API.Before we can use the HTTPClient, we need to add as an import in our app's /src/app/app.module.ts file:
// Other imports removed for brevity
import { HttpClientModule } from '@angular/common/http'; // <-Add here
@NgModule({
declarations: [
// Removed for brevity
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule, // <-Add here
],
providers: [],
bootstrap: [AppComponent]
})
Great!Next, let's open up the /src/app/users/users.component.ts file and import our service:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs';
To display the results, we're going to use an Observable, so we're importing it here, too.In the class, add:
export class UsersComponent implements OnInit {
users$: Object;
constructor(private data: DataService) { }
ngOnInit() {
this.data.getUsers().subscribe(
data => this.users$ = data
);
}
}
In the constructor, we're creating an instance of our service. Then, within the lifecycle hook ngOnInit() (this runs when the component loads), we're calling our getUsers() method and subscribing to it. Inside, we're binding our users$ object to the result returned by the API.Next, open up /src/app/users/users.component.html:
<h1>Users</h1>
<ul>
<li *ngFor="let user of users$">
<a routerLink="/details/{{user.id}}">{{ user.name }}</a>
<ul>
<li>{{ user.email }}</li>
<li><a href="http://{{ user.website }}">{{ user.website }}</a></li>
</ul>
</li>
</ul>
Whenever you wish to iterate over an array or array of objects, you use the Angular directive *ngFor. We then use interpolation brackets to call upon the properties of the returned object to display them in the browser!If you save this and refresh, you should now see a list of users and their information:
Angular 6 HTTP Client
Reviewed by Pakainfo
on
August 08, 2018
Rating:
No comments: