0% encontró este documento útil (0 votos)
98 vistas8 páginas

Proyecto AngularCLI

Este documento describe una aplicación Angular que gestiona clientes. Define clases para el modelo de cliente, un servicio para realizar las operaciones CRUD, y componentes para mostrar una lista de clientes y un formulario para crear/editar clientes.

Cargado por

Ariel Cupertino
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
98 vistas8 páginas

Proyecto AngularCLI

Este documento describe una aplicación Angular que gestiona clientes. Define clases para el modelo de cliente, un servicio para realizar las operaciones CRUD, y componentes para mostrar una lista de clientes y un formulario para crear/editar clientes.

Cargado por

Ariel Cupertino
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 8

Proyecto AngularCLI

cliente.ts

export class Cliente {


id:number;
nombre: string;
apellido:string;
email:string;
createAt:string;
}

cliente.service.ts

import { Injectable } from '@angular/core';


import {CLIENTES} from './clientes.json';
import {Cliente} from './cliente';
import { Observable, of , throwError} from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import swal from 'sweetalert2';
import { Router } from '@angular/router';

@Injectable({
providedIn: 'root'
})
export class ClienteService {

private urlEndPoint: string =


'http://localhost:8088/curso_udemy/clientes';

private httpHeaders = new HttpHeaders({


'Content-Type':'application/json'
});

constructor(private http:HttpClient, private router:Router) { }

getClientes(): Observable<Cliente[]> {
//return of(CLIENTES);
return this.http.get(this.urlEndPoint).pipe(
map(response => response as Cliente[])
);
}
create(cliente:Cliente):Observable<any>{
return this.http.post<any>(this.urlEndPoint, cliente, {headers:
this.httpHeaders}).pipe(
catchError(e =>{
console.log('Error al crear cliente',e.error.mensaje)
swal.fire('Error al crear cliente:
'+e.error.mensaje,e.error.error,'error')
return throwError(e);
})
);
}

getCliente(id:number): Observable<Cliente>{
return this.http.get<Cliente>(`${this.urlEndPoint}/${id}`).pipe(
catchError ( e =>{
this.router.navigate(['/clientes']);
console.log('Error:',e.error.mensaje)
swal.fire('Error al editar: '+e.error.mensaje,e.error.error,'error')
return throwError(e)
})
);
}

update(cliente: Cliente): Observable<Cliente>{


return this.http.put<Cliente>(`${this.urlEndPoint}/${cliente.id}`,
cliente, {headers: this.httpHeaders}).pipe(
catchError(e =>{
console.log('Error al editar cliente',e.error.mensaje)
swal.fire('Error al editar cliente:
'+e.error.mensaje,e.error.error,'error')
return throwError(e);
})
);
}

delete(id: number): Observable<Cliente>{


return this.http.delete<Cliente>(`${this.urlEndPoint}/${id}`, {headers:
this.httpHeaders}).pipe(
catchError(e =>{
console.log('Error al borrar cliente',e.error.mensaje)
swal.fire('Error al borrar cliente:
'+e.error.mensaje,e.error.error,'error')
return throwError(e);
})
);
}

clientes.component.html

<div class="card">
<div class="card-header">Clientes</div>
<div class="card-body">
<h5 class="card-title">Listado de clientes</h5>
<div class="my-2 text-left">
<button class="btn btn-rounded btn-primary" type="button"
[routerLink]="['/clientes/form']">
Crear Cliente
</button>
</div>
<div *ngIf="clientes?.length==0" class="alert alert-info">
<span>No hay registros en la base de datos Clientes.</span>
</div>
<table class="table table-bordered table-striped"
*ngIf="clientes?.length>0">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">Correo</th>
<th scope="col">Creado en</th>
<th>editar</th>
<th>eliminar</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let cliente of clientes">
<th scope="row">{{ cliente.id }}</th>
<td>{{ cliente.nombre }}</td>
<td>{{ cliente.apellido }}</td>
<td>{{ cliente.email }}</td>
<td>{{ cliente.createAt }}</td>
<td>
<button type="button" name="editar"
[routerLink]="['/clientes/form', cliente.id]" class="btn btn-primary btn-
sm">editar</button>
</td>
<td>
<button type="button" name="eliminar"
(click)='delete(cliente)' class="btn btn-danger btn-sm">eliminar</button>
</td>
</tr>
</tbody>
</table>

</div>
</div>

clientes.component.ts

import { Component, OnInit } from '@angular/core';


import {Cliente} from './cliente';
import {ClienteService} from './cliente.service';
import swal from 'sweetalert2'

@Component({
selector: 'app-clientes',
templateUrl: './clientes.component.html',
styleUrls: ['./clientes.component.css']
})
export class ClientesComponent implements OnInit {

clientes: Cliente[];

constructor(private clienteService: ClienteService) { }

ngOnInit() {
this.clienteService.getClientes().subscribe(
clientes => this.clientes = clientes
);
}

delete(cliente: Cliente): void {


swal.fire({
title: 'Está seguro?',
text: `¿Seguro que desea eliminar al cliente ${cliente.nombre}
${cliente.apellido}?`,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar!',
cancelButtonText: 'No, cancelar!',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
reverseButtons: true
}).then((result) => {
if (result.value) {

this.clienteService.delete(cliente.id).subscribe(
response => {
this.clientes = this.clientes.filter(cli => cli !== cliente)
swal.fire(
'Cliente Eliminado!',
`Cliente ${cliente.nombre} eliminado con éxito.`,
'success'
)
}
)

}
})
}

clientes.json.ts

import {Cliente} from './cliente';

export const CLIENTES: Cliente[] = [

{id:1,nombre:'Ariel',apellido:'Cupertino',email:'[email protected]',
createAt:' '+ new Date()},
{id:2,nombre:'Juan
Camilo',apellido:'Perez',email:'[email protected]',createAt:' '+ new
Date()},
{id:3,nombre:'Ana
Lilia',apellido:'Torroja',email:'[email protected]',createAt:' '+ new
Date()},

{id:4,nombre:'Miguel',apellido:'Juarez',email:'[email protected]',crea
teAt:' '+ new Date()},

{id:5,nombre:'Camila',apellido:'Corona',email:'[email protected]',creat
eAt:' '+ new Date()},

{id:6,nombre:'Irinea',apellido:'Fajardo',email:'[email protected]',
createAt:' '+ new Date()}
];

form.component.html

<div class="card bg-dark text-white">


<div class="card-header">{{ titulo }}</div>
<div class="card-body">

<form>
<div class="form-group row">
<label for="nombre" class="col-form-label col-sm-2">Nombre</label>
<div class="col-sm-6">
<input type="text" class="form-control"
[(ngModel)]="cliente.nombre" name="nombre">
</div>
</div>

<div class="form-group row">


<label for="apellido" class="col-form-label col-sm-
2">Apellido</label>
<div class="col-sm-6">
<input type="text" class="form-control"
[(ngModel)]="cliente.apellido" name="apellido">
</div>
</div>

<div class="form-group row">


<label for="email" class="col-form-label col-sm-2">Email</label>
<div class="col-sm-6">
<input type="text" class="form-control"
[(ngModel)]="cliente.email" name="email">
</div>
</div>

<div class="form-group row">


<div class="col-sm-6">
<button class="btn btn-primary" role="button" (click)='create()'
*ngIf="!cliente.id else elseBlock">Crear</button>

<ng-template #elseBlock>
<button class="btn btn-primary" role="button"
(click)='update()'>Editar</button>
</ng-template>
</div>
</div>
</form>

</div>
</div>

form.component.ts

import { Component, OnInit } from '@angular/core';


import { Cliente } from './cliente';
import { ClienteService } from './cliente.service';
import { Router, ActivatedRoute } from '@angular/router';
import swal from 'sweetalert2'

@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
private titulo: string = 'Formulario de clientes';
private cliente:Cliente = new Cliente();

constructor(private clienteService: ClienteService,


private router:Router,
private activatedRoute: ActivatedRoute) {}

ngOnInit() {
this.cargarCliente()
}

cargarCliente(): void{
this.activatedRoute.params.subscribe(params => {
let id = params['id']
if(id){
this.clienteService.getCliente(id).subscribe( (cliente) =>
this.cliente = cliente)
}
})
}

public test():void{
swal.fire('Cliente creado',`El cliente ha sido creado
exitosamente`,'success')
}

public create():void{
this.clienteService.create(this.cliente).subscribe(
json => {
this.router.navigate(['/clientes'])
swal.fire('Cliente creado',` ${json.mensaje} : El cliente
${json.cliente.nombre} ha sido creado exitosamente`,'success')
}
);
}

public update():void{
this.clienteService.update(this.cliente)
.subscribe( cliente => {
this.router.navigate(['/clientes'])
swal.fire('Cliente Actualizado', `Cliente ${cliente.nombre}
actualizado con éxito!`, 'success')
}
);
}

También podría gustarte