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





jueves, 6 de julio de 2017

Angular 2 - 14) Animaciones


Objetivo:
  • Aplicar animación trigger, state, transform


  1. Abrir el proyecto package.json y agregar la dependencia del módulo de animación


"dependencies": {
  "@angular/animations": "~4.2.0",
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",
  "core-js": "^2.4.1",
  "rxjs": "^5.1.0",
  "zone.js": "^0.8.4"
},


  1. Abrir una consola y ejecutar npm install para instalar la dependencia de animations
  2. Dentro de app crear una carpeta llamada animations.
  3. Dentro de la carpeta animations crear un archivo llamado animations.components.css y agregar el siguiente contenido


p {
  width:200px;
  background:lightgray;
  margin: 100px auto;
  text-align:center;
  padding:20px;
  font-size:1.5em;
}


  1. Dentro de la carpeta animations crear un archivo llamado animations.component.html y agregar el siguiente contenido:


<p [@myAwesomeAnimation]='stateAnimation' (click)="animateMe()">Mi animacion</p>


  1. Dentro de la carpeta animations crear un archivo llamado animations.component.ts y agregar el siguiente contenido:


import { Component, OnInit } from '@angular/core';
import { trigger,state,style,transition,animate } from '@angular/animations';


@Component({
selector: 'app-animations',
templateUrl: './animations.component.html',
styleUrls: ['./animations.component.css'],
animations:  [
  trigger('myAwesomeAnimation', [
      state('small', style({
          transform: 'scale(1)',
      })),
      state('large', style({
          transform: 'scale(1.2)',
      })),
      transition('small => large', animate('100ms',style({
          transform: 'translateY(40px)'
      }))),
  ]),
]
})
export class AnimationsComponent implements OnInit {


stateAnimation: string = 'small';
 constructor() { }


animateMe() {
  this.stateAnimation = (this.stateAnimation === 'small' ? 'large' : 'small');
}


ngOnInit() {


}


}


Para los puntos anteriores revisar la opción de crear el component desde la consola. Mirar este link: https://github.com/angular/angular-cli/wiki/generate-component


  1. Abrir el archivo llamado app.module.ts y agregar lo siguiente:


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ROUTES } from './app.route';


import { BrowserAnimationsModule } from '@angular/platform-browser/animations';


import { AppComponent } from './app.component';
import { UsersComponent } from './users/users.component';
import { UserFormComponent } from './user-form/user-form.component';
import { UserService } from './shared/services/user.service';
import { AnimationsComponent } from './animations/animations.component';


@NgModule({
declarations: [
  AppComponent,
  UsersComponent,
  UserFormComponent,
  AnimationsComponent
],
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  ROUTES,
  BrowserAnimationsModule
],
providers: [
  UserService
],
bootstrap: [AppComponent]
})
export class AppModule { }


  1. Abrir el archivo app.route.ts y actualizar el contenido con esta información:


import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


import { AppComponent } from './app.component';
import { UsersComponent } from './users/users.component';
import { UserFormComponent } from './user-form/user-form.component';
import { AnimationsComponent } from './animations/animations.component';


export const ROUTE: Routes = [
  { path: '', redirectTo: 'users', pathMatch: 'full' },
  { path: 'users', component: UsersComponent },
  { path: 'new-user', component: UserFormComponent },
  { path: 'animations' , component: AnimationsComponent }
];


export const ROUTES: ModuleWithProviders = RouterModule.forRoot(ROUTE);


  1. Desde la consola ejecutar ng serve