How to handle connection errors, for example CORS


#1

How to handle connection errors, for example CORS. Since previously I could not log in to an ApiRest and in the App I could not capture the error. I could only see it in the browser console.

Function from where I invoke the Service getResumenMovimientos:

import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import { ServiceRestProvider } from '../../providers/service-rest/service-rest';
import { LoadingController } from 'ionic-angular';
import { AlertController, Platform } from "ionic-angular";

@Component({
    selector: 'page-coperativa_resumen',
    templateUrl: 'coperativa_resumen.html'
  })
  export class ResumenCooperativaPage {
    loading: any;
    resumen:any;
    constructor(public navCtrl: NavController,
        private menuCtrl: MenuController,
        public service: ServiceRestProvider,
        public loadingController:LoadingController,
        private alertCtrl: AlertController) {
            this.getResumen();

      }

      getResumen(){
        this.loading = this.loadingController.create({ content: "Buscando información ,espere por favor..." });
        this.loading.present();
        console.log("Ejecutando getResumen");
        this.service.getResumenMovimientos()
          .then(data => {
            console.log("Data recibida");
            console.log(data);
            this.loading.dismissAll();

            this.resumen = data;
          }, err => {
            console.log("Error al recibir data");
            console.log(err);
            this.loading.dismissAll();
            this.alertCtrl.create({
              title: "Error",
              subTitle: 'Mensajes: ' + err.message  ,
              buttons: ["OK"]
            }).present();
          });
      }
  }

This is the service:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AlertController, Platform } from "ionic-angular";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import * as jwt_decode from "jwt-decode";
import { URLSearchParams } from '@angular/http';
import { HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage';

@Injectable()
export class ServiceRestProvider {

  Token: any;
  token_full: any;
  jwt_token: any;
  token_full_json: any;
 
  constructor(public http: HttpClient,
    private alertCtrl: AlertController,
    private platform: Platform,
    private storage: Storage) {
    console.log('Entrando a ServiceRestProvider Provider y cargar storage');
    this.cargar_storage();
  }

  public activo(): boolean {

    if (this.Token != "") {
      console.log("true");
      return true;

    } else {
      console.log("false");
      return false;
    }
  }

  ingresar(codigo: string, usuario: string, contrasena: string) {

    const body = JSON.stringify({
      Codigo: codigo,
      Usuario: usuario,
      Password: contrasena
    });

    const headers = new HttpHeaders().set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT')
      .set('Accept', 'application/json')
      .set('Content-Type', 'application/json; charset=utf-8');

    return this.http.post('http://intsdfca2:84/api/Login', body, { headers: headers})
      .map((resp: any) => {
         console.log("Antes de recibir token");
         
         /*this.alertCtrl.create({
          title: "Token recibido",
          subTitle: resp,
          buttons: ["OK"]
        }).present();*/

        let jwt = jwt_decode(resp);
        console.log(jwt);
   
        let jwt_json1 = JSON.parse(resp);
        this.token_full = jwt_json1["token"];
        
        if (resp.error) {
          
          this.alertCtrl.create({
            title: "Error al iniciar",
            subTitle: jwt['Apellidos'],
            buttons: ["OK"]
          }).present();
        } else {
          //console.log("No hubo error al cargar");
          this.Token = jwt['Token'];
          this.token_full = jwt_json1["token"];
          //console.log(this.Token + this.token_full);
          this.guardar_storage();
        }
      }, err => {
        
        console.log(err);
      }
      );
  }

  private guardar_storage() {
    if (this.platform.is("cordova")) {
      //console.log("El token a guardar en storage es");
      //console.log(this.Token);
      this.storage.set('Token', this.Token);
      this.storage.set('Token_Full', this.token_full);

    } else {
      if (this.Token != "") {
        //console.log("Guardando token");
        localStorage.setItem("Token", this.Token);
        localStorage.setItem("Token_Full", this.token_full);
        //console.log("El token guardado es:");
        //console.log(localStorage.getItem("Token_Full"));
      } else {
        //console.log("Removiendo token del local storage");
        localStorage.removeItem("Token");
        localStorage.removeItem("Token_Full");
      }
    }
  }

  cargar_storage() {
    //console.log("Entrando a cargar local storage");
    let promesa = new Promise((resolve, reject) => {

      if (this.platform.is("cordova")) {
        // dispositivo
        //console.log("Existen items en el local storage dispositivo cordova");
        this.storage.ready()
          .then(() => {

            this.storage.get("Token_Full")
              .then(Token => {
                console.log(Token);
                if (Token != "") {
                  this.Token = Token;
                  this.token_full = Token;
                }
              })
          })
      } else {
        // computadora
        if (localStorage.getItem("Token_Full")) {
          //Existe items en el localstorage
          //console.log("Existen items en el local storage computadora");
          this.token_full = localStorage.getItem("Token_Full");
          //console.log(localStorage.getItem("Token_Full"));
        }
        resolve();
      }
    });
    return promesa;
  }

  getNovedades(FechaInicial: any, FechaFinal: any) {
    console.log("Recibiendo parametros en getNovedades");
    console.log(FechaInicial);
    console.log(FechaFinal);


    console.log("Token en almacenamiento interno getNovedades");
    console.log(localStorage.getItem("Token_Full"));

    const header = new HttpHeaders().set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT')
      .set('Accept', 'application/json')
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Authorization', localStorage.getItem("Token_Full").toString())
      .set('Authorization', 'Bearer ' + localStorage.getItem("Token_Full").toString());

    return new Promise(resolve => {
      this.http.get('http://intsdfca2:84/api/EstadoDeCuenta' + '/12122017/12122018', { headers: header }).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }


  getResumenMovimientos() {
    console.log("Token en almacenamiento interno getResumenMovimientos");
    console.log(localStorage.getItem("Token_Full"));

    const header = new HttpHeaders().set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT')
      .set('Accept', 'application/json')
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Authorization', localStorage.getItem("Token_Full").toString())
      .set('Authorization', 'Bearer ' + localStorage.getItem("Token_Full").toString());
    return new Promise(resolve => {
      this.http.get('http://intsdfca2:84/api/EstadoDeCuenta', { headers: header}).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }
  Cerrar_Sesion() {

    this.token_full = null;
    // guardar storage
    this.guardar_storage();

  }
}

Thanks for the help.


#2

Hola, hablas espanol?

You don’t need to return a promise, the http.get return is an subscriber and when you call the function you need to catch the error.

get<T>(url, retryTimes = 0, noToken = false) {
    let headers = new HttpHeaders();
    if (noToken){
      headers = this.noTokenheader();
    }
    return this.http.get<any>(ENV.api + url, {headers: headers} )
    .map((response) => {
        return response;
    })
    .pipe(
        retry(retryTimes),
        catchError(handleError) // then handle the error
    );
  }

public handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
        // A client-side or network error occurred. Handle it accordingly.
        console.log('An error occurred:', error.error.message);
    } else {
       if(error.status == 401){
          //token issue
          if (this._events){
          this._events.publish('http:401', "Token Expired");
          }
        }

        console.log(error);
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        console.error(
          `Backend returned code ${error.status}, ` +
          `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return Observable.throw(`Something bad happened; please try again later. error Info:  ${error.error.message}`);
};

#3

Thanks for the help. I do not know if it is possible for you to indicate me according to this code, as it should be with the example that you indicated to me.

    import { Component } from '@angular/core';
    import { NavController, MenuController } from 'ionic-angular';
    import { ServiceRestProvider } from '../../providers/service-rest/service-rest';
    import { LoadingController } from 'ionic-angular';
    import { AlertController, Platform } from "ionic-angular";

    @Component({
        selector: 'page-coperativa_resumen',
        templateUrl: 'coperativa_resumen.html'
     })
    export class ResumenCooperativaPage {
    loading: any;
    resumen:any;
    constructor(public navCtrl: NavController,
        private menuCtrl: MenuController,
        public service: ServiceRestProvider,
        public loadingController:LoadingController,
        private alertCtrl: AlertController) {
            this.getResumen();
    
      }
      
      getResumen(){
        this.loading = this.loadingController.create({ content: "Buscando información ,espere por favor..." });
        this.loading.present();
        console.log("Ejecutando getResumen");
        this.service.getResumenMovimientos()
          .then(data => {
            console.log("Data recibida");
            console.log(data);
            this.loading.dismissAll();
          
            this.resumen = data;
          }, err => {
            console.log("Error al recibir data");
            console.log(err);
            this.loading.dismissAll();
            this.alertCtrl.create({
              title: "Error",
              subTitle: 'Mensajes: ' + err.message  ,
              buttons: ["OK"]
            }).present();
          });
          
      }
     }

My service:

import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AlertController, Platform } from "ionic-angular";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage';

@Injectable()
export class ServiceRestProvider {
 
  constructor(public http: HttpClient,
    private alertCtrl: AlertController,
    private platform: Platform,
    private storage: Storage) {
    console.log('Entrando a ServiceRestProvider Provider y cargar storage');
  }

  getResumenMovimientos() {
    console.log("Token en almacenamiento interno getResumenMovimientos");
    console.log(localStorage.getItem("Token_Full"));

    const header = new HttpHeaders().set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT')
      .set('Accept', 'application/json')
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Authorization', localStorage.getItem("Token_Full").toString())
      .set('Authorization', 'Bearer ' + localStorage.getItem("Token_Full").toString());
    return new Promise(resolve => {
      this.http.get('http://intsdfca2:84/api/EstadoDeCuenta', { headers: header}).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }
}

Y si hablo español, saludos.