Servicios Rest con Angular 2

REST (Representational State Transfer) es una arquitectura que se ejecuta sobre HTTP.

RESTful hace referencia a un servicio web que implementa la arquitectura REST.







Implementación con observables
leerDatos(): Observable<Response> {
return this.http
.get(`${this.urlBase}/recurso`);
// En este momento aún no se efectuó la llamada
}getAll(): Observable<Person[]>{
let people$ = this.http
.get(this.baseUrl + '/people', {headers: this.getHeaders()})
.map(mapPersons)
.catch(handleError);
return people$;
}Implementación con observables
escribirDatos(unDato): Observable<Response> {
// Los envíos de información deben configurarse a mano
// esto es fácilmente generalizable y reutilizable
let body = JSON.stringify(unDato);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
// declarar la llamada y retornar el observable
// las variables de configuración y los datos, van como parámetros
if (unDato._id) {
return this.http
.put(`${this.urlBase}/recurso/${unDato._id}`, body, options);
} else {
return this.http
.post(`${this.urlBase}/recurso`, body, options);
}
} save(person: Person) : Observable<Response>{
return this.http
.put(`${this.baseUrl}/people/${person.id}`,
JSON.stringify(person),
{headers: this.getHeaders()});
}Consumir desde el componente
ngOnInit() {
this.datosService
.leerDatos()
.subscribe(res => {
this.datos = res.json();
});
}ngOnInit(){
this.peopleService
.getAll()
.subscribe(
/* happy path */ people => this.people = people,
/* error path */ error => this.errorMessage = error,
/* onComplete */ () => this.isLoading = false);
}Vamos al ejemplo!

Fuentes
-
http://academia-binaria.com/comunicaciones-http-observables-con-angular2/ -
https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/
Servicios Api Rest ful
By Milena Suarez
Servicios Api Rest ful
- 25