Writing an HTTP request with Angular2

Writing an HTTP request with Angular2 can be tricky at first! So I decided to write this blog post to hopefully help someone out! So lets get started we’ll start with a basic Angular2 component much like the in the previous post.

import { Component } from '@angular/core';
import { myAppService } './myApp.service';
@Component({
selector: 'my-app',
template: `
<h3>Users</h3>
<ul *ngFor="let user of users">
<li>
{{user.name}}
</li>
</ul>
`
})
export Class MyAppComponent {
private users = [];
  constructor(
private myAppService: myAppService,
) {}
}

You’ll notice the *ngFor statement here this is basically just a for loop inside of the template. It loops through the private users variable and sets the individual user to the user variable there. The next thing you’ll notice is the constructor this allows use to use the service that we’re about to create.

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
exportClass MyAppService {
constructor (private http: Http) {}
getUsers ():Observable<any> {
return this.http.get('/api/users')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}

Here the first new thing is the @Injectable decorator. This lets Angular2 know that our class can be used with the dependency injector. The next thing will probably be the use of the Observable<any> syntax inside on getUsers. This basically sets up an Observable using typescript and telling it what value types can be inside of that Observable.

An observable is a just a collection that happens of time and you can do kinds of cool things with those collections! But for now we are just mapping the results of our API request using our extractData function so that we get our data back in a useful format for us. And lastly we just handle errors.

Now if we look back into our myApp component we can use the service we just created to make some HTTP requests to our api endpoints and render the response on the page.

import { Component, OnInit } from '@angular/core';
import { myAppService } './myApp.service';
@Component({
selector: 'my-app',
template: `
<h3>Users</h3>
<ul *ngFor="let user of users">
<li>
{{user.name}}
</li>
</ul>
`
})
export Class MyAppComponent implements OnInit {
private users = [];
  constructor(
private myAppService: myAppService,
) {}
  ngOnInit() {
this.getUsers();
};
  getUsers() {
this.myAppService.getUsers()
.subscribe(
data => this.users = data,
error => this.errorMessage = <any>error
);
}
}

Okay so here I’ve added OnInit to my imports for angular core and I have also added ‘implements OnInit’ to export Class MyAppComponent. This way of doing it is a convention that Angular2 recommends. What this is basically saying is that this class wants something done on initialization and what I’m telling it to do is invoke the getUsers function on the class. This getUsers function calls the getUsers function from the service and then subscribes to that data it then sets the users variable equal to that data and now our page should render the names of users as a list!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.