Objectivo:
- Hacer una llamada POST para agregar un nuevo usuario.
- Abrir el archivo user.services.ts y agregar un nuevo método llamado saveUser como se muestra a continuación:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs';
import { User } from '../models/user';
const SERVER_REST_API_URL = "http://localhost:3000/users/";
@Injectable()
export class UserService {
private http: Http;
constructor(http:Http) {
this.http = http;
}
getUsers() {
return this.http.get(SERVER_REST_API_URL)
.map(res => res.json());
}
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(SERVER_REST_API_URL, body, options);
}
}
- Abrir el archivo llamado user-form.component.ts y modificar el método submit para que utilice el servicio llamado userService.
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { User } from '../shared/models/user';
import { UserService } from '../shared/services/user.service';
@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {
@Output() userCreatedEvent = new EventEmitter();
newUser: User;
userService:UserService;
active:boolean= true;
constructor(userService: UserService) {
this.userService = userService;
}
onSubmit() {
this.userService.saveUser(this.newUser)
.subscribe(()=>{
this.userCreatedEvent.emit({user: this.newUser});
this.active = false;
this.newUser = new User("","","");
setTimeout(() => { this.active = true; }, 0);
});
}
ngOnInit() {
this.newUser = new User("","","");
}
}
- Abrir el archivo llamado user-form.component.ts y actualizar el form de la siguiente manera:
<form #userForm="ngForm" (ngSubmit)="onSubmit()" *ngIf="active">
<div class="form-group" [class.has-error]="name.invalid && name.touched">
<input type="text" placeholder="Nombre" class="form-control" name="name" required
[(ngModel)]="newUser.name" #name="ngModel">
<span class="hel-block" *ngIf="name.invalid && name.touched">El nombre es requerido</span>
</div>
<div class="form-group" [class.has-error]="username.invalid && username.touched">
<input type="text" placeholder="Nombre de usuario" class="form-control" name="username" required
[(ngModel)]="newUser.username" #username="ngModel">
<span class="hel-block" *ngIf="username.invalid && username.touched">El nombre de usuario es requerido</span>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block" [disabled]="userForm.invalid">
Crear Usuario
</button>
</form>
- Abrir una consola y ejecutar ng serve. Con esto ya podemos agregar un nuevo usuario a la lista.
No hay comentarios:
Publicar un comentario