It may be a good idea to encapsulate the HTTP handling logic in its own class. The following class exposes a method for getting Posts. It calls the http.get()
method and calls .map
on the returned Observable
to convert the Response
object to a Post
object.
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
@Injectable()
export class BlogApi {
constructor(private http: Http) {
}
getPost(id: number): Observable<Post> {
return this.http.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.map((response: Response) => {
const srcData = response.json();
return new Post(srcData)
});
}
}
The previous example uses a Post
class to hold the returned data, which could look as follows:
export class Post {
userId: number;
id: number;
title: string;
body: string;
constructor(src: any) {
this.userId = src && src.userId;
this.id = src && src.id;
this.title = src && src.title;
this.body = src && src.body;
}
}
A component now can use the BlogApi
class to easily retrieve Post
data without concerning itself with the workings of the Http
class.