Angular 2 http

Preparation

Angular 2 comes with a built-in http client to easily make RESTful calls. The http client is provided in the HttpModule. So we first need to load it in the module file.

1
2
3
4
5
6
7
8
9
import {HttpModule} from '@angular/http';
@NgModule({
imports: [HttpModule...],
declarations: [...],
providers: [...],
bootstrap: [AppComponent]
})
export class AppModule {
}

Then in the service class we can ask the Angular to inject the Http service to us.

1
2
3
4
5
6
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
@Injectable()
export class MyService {
constructor(private http: Http){}
}

Retrieve data

Now we are ready to use the http instance to access the backend service. It is simple to use http GET to access a backend resource.

1
2
let url = 'serviceUrl';
this.http.get(url);

The only required argument is the url, e.g ‘/employee/123’. All http calls in Angular 2 is asynchronous. It returns Observable<Response> which needs to be subscribed to retrieve the returned value.

1
this.http.get(url).subscribe(resp => console.log(resp));

We most of the time also need to extract the real meaningful value or check the http status from the http Response.

  • To check the http status.

    1
    let status = resp.status;
  • To get the text value of from the response body

    1
    let txt = resp.text();
  • To convert the response body to a json

    1
    let value = resp.json() as <YourType>;

So if we have a service class called EmployeeService which can retrieve an employee, we can use http client like this:

1
2
3
4
5
6
7
8
this.http.get(svcUrl)
.map(resp => resp.json() as Employee)
.catch(error => {
if (error.status === 401) {
this.router.navigate(['/login']);
}
})
.subscribe(employee => console.log('Employee is ' + employee));

Submit data

We use operation POST to submit a request to the backend. It requires not only a URL string but also a payload object and an optional header to indicate the content type.

Text payload

The text payload can be either be a json string if the ‘Content-Type’ is set to ‘application/json’ in the header or a plain string like ‘p1=v1&p2=v2&p3=v3’ if the ‘Content-Type’ is set to ‘application/x-www-form-urlencoded’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import {Headers, RequestOptions} from "@angular/http";
let isJson;
......
let svcUrl = '/user';
let parameters = isJson?
JSON.stringify({name: 'John Doe', age: 30}) :
'name=' + encodeURIComponent('John Doe') + "&age=30";
this.http.post(svcUrl, parameters, this.getHeader(isJson));
getHeader(isJson: boolean): RequestOptions {
let headers = new Headers();
if (!isJson) {
headers.append('Content-Type', 'application/x-www-form-urlencoded');
} else {
headers.append('Content-Type', 'application/json');
}
return new RequestOptions({ headers: headers });
}

URLSearchParams payload

If we want to submit an raw javascript object, we have to serialize it to a string. Angular 2 provides a URLSearchParams class to simply this process.

1
2
3
4
5
6
let form = {name: 'lli', age: 10};
let input = new URLSearchParams();
for (let p in form) {
input.set(p, form[p]);
}
this.http.post(svcUrl, input).subscribe(resp => console.log(resp));

When Angular 2 detects that the payload is an URLSearchParams object, it will call its toString method and automatically set the ‘Content-Type’ to ‘application/x-www-form-urlencoded’.

Object payload

There is a another short path to submit a json string payload by just simply passing the raw javascript object to the POST method. Under the hood, Angular 2 will automatically set the ‘Content-Type’ to ‘application/json’ and apply JSON.stringify on the object.

1
2
3
4
5
6
this.http.post(svcUrl, {name: 'John Doe', age: 30}).subscribe(resp => console.log(resp));
equals to
this.http.post(svcUrl, JSON.stringify({name: 'John Doe', age: 30}), this.getHeader(true))
.subscribe(resp => console.log(resp));