I've been getting into angular recently and I would like to know what is the best way to capture and display the errors I receive from a REST API server, I have the following:
Service
import { Injectable } from '@angular/core';
import { Usuario } from 'src/app/models/usuario.model';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UsuarioService {
constructor(public _http: HttpClient) {}
crearUsuario( usuario: Usuario){
let url = `http://localhost:3000/usuario`;
return this._http.post(url, usuario);
}
}
Component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { UsuarioService } from '../services/service.index';
import { Usuario } from '../models/usuario.model';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./login.component.css']
})
export class RegisterComponent implements OnInit {
forma: FormGroup;
constructor( public _usuarioService: UsuarioService) { }
ngOnInit() {
this.forma = new FormGroup({
// Valor por defecto y validaciones
nombre: new FormControl('test', Validators.required ),
correo: new FormControl('[email protected]', [Validators.required, Validators.email]),
password: new FormControl('123456', Validators.required),
confPassword: new FormControl('123456', Validators.required),
condiciones: new FormControl(true)
}, { validators: this.verificarPassword('password', 'confPassword')});
}
verificarPassword( campo1: string, campo2: string){
return ( group: FormGroup) => {
let pass1 = group.controls[campo1].value;
let pass2 = group.controls[campo2].value;
if( pass1 === pass2 ) return null;
return {
sonIguales: true
}
}
}
registrarUsuario(forma: FormControl){
console.log(forma);
let usuario = new Usuario(
this.forma.value.nombre,
this.forma.value.correo,
this.forma.value.password
)
this._usuarioService.crearUsuario(usuario).subscribe( result =>{
console.log(result );
});
}
}
The error returned is a status 500
if there is a failure in the registration and a status 200
if the request is successful.
What I want to do is give the user more clarity when creating the account, showing where the error comes from, in this case it would be because the email already exists.
first of all, Thanks :)