How to call reading HTTP responses

Asked

Viewed 2,698 times

1

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

An example as 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 Template - Return:

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

I managed to reach 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 take inside DATA now and get this Entity that is inside DATA.

  • The question is how to know which http error code your backend returned?

  • The question is how to take here in Angular these returns for example when the error is 404, 500 or other. I want to take Response here in Angular and treat these errors to send messages on the screen.

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 send no item to the Observer and immediately issue an error notification. Such notification may be manipulated in the callback error.

To handle the error inside 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
            );
    }
}
  • That friend, that’s exactly what I wanted, but how do I get this information after where it’s calling in the Angular Component? because he’s returning an Observable.

  • @And in case you want to pass the error code to the component?

  • Yeah, that’s right

  • @And then I edited the answer.

  • I’m almost on my way, I included here exactly what I want to do, for you to understand the JSON that I put, is exactly what will come back in this case I need to take the Code and the Message that is within the Entity within the JSON pass to the Component and take this Message and display on the screen.

  • I made some more updates in Source Code, I’m almost able to do what I wanted to do, if you can help me or have some better way, thank you. I need to know now how I get the Entity inside the DATA variable inside the Component that is coming back right now, plus if there is any better way I am willing to see.

  • @And the best part data.context.entity.code and data.context.entity.message. If the same JSON format is returned when there is an error in the backend, it follows the same logic: err.context.entity.code and err.context.entity.message.

  • core.js:1427 ERROR Typeerror: Cannot read Property 'Entity' of Undefined at Safesubscriber.Eval [as _next] (usuario-login.component.ts:46) at Safesubscriber. __tryOrUnsub (Subscriber.js:240) at Safesubscriber.next (Subscriber.js:187) at Subscriber. _next (Subscriber.js:128) at Subscriber.next (Subscriber.js:92) at Catchsubscriber.Subscriber. _next (Subscriber.js:128) at Catchsubscriber.Subscriber.next (Subscriber.js:92) at Mapsubscriber. _next (map.js:85) at Mapsubscriber.Subscriber.next (Subscriber.js:92) at Xmlhttprequest.onload (http.js:1591)

  • Can’t read the Entity property.

  • I’m discovering friend actually I have to pick up as date[0]. Entity always arrives as an Array in Response, only now as I access the code and the message that is inside Entity?

  • So far it works date[0]. Entity, but data[0].entity.code and data[0]. message does not work.

  • @You can print the contents of data and paste here so we can analyze?

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.