How to call read HTTP responses

1

I would like to bring some error messages in JSON to this class below and I do not know how to do this, my connection to the Database is OK and returning the right JSON, I would like to read the Response that I am sending back , but I do not know how to do this, I searched the internet and did not find it, I would like for example to do the following example if I see a Http 404 error I do something, 500 something else error and success something else actually show a Modal in screen showing these messages that would come in Response, does anyone have an idea to do this here in the service? on the return of JSON.

An example like I wanted:

saveUsuario(usuario: Usuario): Observable<Usuario> {
    if (http code 404 ) {
        chama modal
    } else if (http code 500) {
        chama modal
    }
}

My Class - Service:

import { Injectable } from '@angular/core';
import { Usuario } from "./usuario";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';
import { Observable } from "rxjs/Observable";

@Injectable()
export class UsuarioService {

  private apiUrl = 'http://localhost:8080/usuario';

  constructor(private http: Http) {
  }

  saveUsuario(usuario: Usuario): Observable<Usuario> {
    return this.http.post(this.apiUrl, usuario)
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

  deleteUsuarioById(codigoUsuario: number): Observable<boolean> {
    return this.http.delete(this.apiUrl + '/' + codigoUsuario)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

  updateUsuario(usuario: Usuario): Observable<Usuario> {
    return this.http.put(this.apiUrl, usuario)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

  findById(codigoUsuario: number): Observable<Usuario> {
    return this.http.get(this.apiUrl + '/' + codigoUsuario)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Error'));
  }

  findAll(): Observable<Usuario[]>  {
    return this.http.get(this.apiUrl)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

  login(loginUsuario: string, senhaUsuario: string): Observable<Response> {
    return this.http.get(this.apiUrl + '/login/' + loginUsuario + '/senha/' + senhaUsuario)
      .map((res: Response) => {
        if (res) {
          if (res.status === 201) {
            return [{ status: res.status, json: res }]
          } else if (res.status === 200) {
            return [{ status: res.status, json: res }]
          }
        }
        }).catch((error: any) => {
          if (error.status === 500) {
            return Observable.throw(new Error(error.status));
          }
          else if (error.status === 400) {
            return Observable.throw(new Error(error.status));
          }
          else if (error.status === 409) {
            return Observable.throw(new Error(error.status));
          }
          else if (error.status === 406) {
            return Observable.throw(new Error(error.status));
          }});
  }

}

My Class - Component:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from "@angular/forms";
import { UsuarioService } from "../usuario.service";
import { Usuario } from "../usuario";
import { ActivatedRoute, Router } from '@angular/router';
import { HttpModule } from '@angular/http';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-usuario-login',
  templateUrl: './usuario-login.component.html',
  styleUrls: ['./usuario-login.component.css'],
    providers: [UsuarioService]
})
export class UsuarioLoginComponent implements OnInit {

    private usuarioForm : FormGroup;

    constructor(private activatedRoute: ActivatedRoute,
                private router: Router,
                private usuarioService: UsuarioService,
                private formBuilder: FormBuilder,
                private toastr: ToastrService) {

    this.createForm();
  }

  createForm() {
    this.usuarioForm = this.formBuilder.group({
      loginUsuario: ['', Validators.required ],
      senhaUsuario: ['', Validators.required ]
    });
  }

  ngOnInit() {
  }

  error: string;
  data: any;

  onSubmit(loginUsuario, senhaUsuario) {
    this.usuarioService.login(loginUsuario, senhaUsuario)
       .subscribe(
         data => this.data = data,
         err  => this.error = <any>err.message);
  }

}

JSON Model - Return:

{
    "code": 4,
    "message": "Sucesso"
}

I was able to get to my Componenent with JSON like this:

My Service:

  login(loginUsuario: string, senhaUsuario: string): Observable<Response> {
    return this.http.get(this.apiUrl + '/login/' + loginUsuario + '/senha/' + senhaUsuario)
      .map((res: Response) => {
        if (res) {
          if (res.status === 201) {
            return [{ json: res._body }]
          } else if (res.status === 200) {
            return [{ json: res._body }]
          }
        }
        }).catch((error: any) => {
          if (error.status === 500) {
            return Observable.throw(new Error(error.status));
          }
          else if (error.status === 400) {
            return Observable.throw(new Error(error.status));
          }
          else if (error.status === 409) {
            return Observable.throw(new Error(error.status));
          }
          else if (error.status === 406) {
            return Observable.throw(new Error(error.status));
          }});
  }

My Component:

  onSubmit(loginUsuario, senhaUsuario) {

    this.usuarioService.login(loginUsuario, senhaUsuario).subscribe(
       data => {
         console.log(data);
       },
       error => {
         console.error("Error saving food!");
         return Observable.throw(error);
       }
    );

How to get inside the DATA now and get this Entity that is inside the DATA.

    
asked by anonymous 14.01.2018 / 03:06

1 answer

1

You can do something like this:

saveUsuario(usuario: Usuario): Observable<Usuario> {
    return this.http.post(this.apiUrl, usuario)
        .catch((error: any) => {
            return Observable.throw(error);
        });
}

Using Observable.throw you issue no items to the Observer and immediately issues an error notification. Such notification can be handled in the callback error.

To handle the error within your component:

@Component({
    selector: 'meu-app',
    template: '
        <div>Código: {{ erro.code }}</div>
        <div>Mensagem: {{ erro.message }}</div>
    '
})
export class AppComponent {
    erro: any;
    data: any;

    constructor(private usuarioadminservice: UsuarioAdminService ) {}
    ngOnInit() {
        this.usuarioadminservice.saveUsuario(null)
            .subscribe(
                data => this.data = data,
                err  => this.erro = <any>err
            );
    }
}
    
14.01.2018 / 15:51