sábado, 8 de julio de 2017

Angular 2 - 15) Soportar diferentes llamadas a servicios Rest API



Objetivo:
  • Soportar múltiples entornos(desarrollo-producción)


  1. Abrir una consola y dentro del proyecto angular-faster ejecutar este comando:


json-server database.json


Levante un servidor en el puerto 3000


  1. Abrir una nueva consola y dentro del proyecto angular-faster ejecutar este comando:


json-server --port 3001 database.json


Levanta un servidor en el puerto 3001


  1. Abrir el archivo llamado environment.ts y agregar la siguiente información:


export const environment = {
production: false,
apiEndPoint: "http://localhost:3000"
};


  1. Abrir el archivo llamado environment.prod.ts y agregar la siguiente información:


export const environment = {
production: true,
apiEndPoint: "http://localhost:3001"
};


  1. Abrir el archivo llamado user.service.ts y actualizar la información siguiente:


import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs';
import { User } from '../models/user';
import { environment } from '../../../environments/environment'


const SERVER_REST_API_URL = "http://localhost:3000/users/";


@Injectable()
export class UserService {


private http: Http;
private serverRestAPIUrl: string;


constructor(http:Http) {
  this.http = http;
  this.serverRestAPIUrl = environment.apiEndPoint + "/users";
}


getUsers() {
  return this.http.get(this.serverRestAPIUrl)
      .map(res => res.json());
}


deleteUser(id) {
  return this.http.delete(this.serverRestAPIUrl + id);
}


saveUser(user:User) {
  let body = JSON.stringify({
      "id": user.id,
      "name": user.name,
      "username": user.username
  });
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this.http.post(this.serverRestAPIUrl, body, options);
}


}


  1. Abrir una consola y dentro del proyecto angular-faster ejecutar los siguiente:


ng serve --env=prod


  1. Abrir en un brower la url: http://localhost:4200 y analizar que las consultas en la consola se ejecutan contra el entorno que fue definido para producción




  1. Analizar cómo agregar un nuevo entorno además del de producción. Para ello se debe actualizar el archivo llamado angular-cli.json





No hay comentarios:

Publicar un comentario