App only shows data in browser, in cell phone not


#1

I have a problem with an app, on a cell phone I can only log in but not get the data from the database.

If I run the app from the browser, I can log in and get the data from the database.

I do not know what could be failing, I checked everything and I do not find that it could be wrong.

Function from where I invoke the service:

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.getResumen2();

  }

  getResumen2() {

   // this.loading = this.loadingController.create({ content: "Buscando información ,espere por favor ResumenMovimientos2..." });
    //this.loading.present();
    //this.loading.dismissAll();
    console.log("Ejecutando getResumen2");
    this.service.getResumenMovimientos2()
      .subscribe(data => {

        if (data.error) {
          //this.loading.dismissAll();
          // manejo de errores
          this.alertCtrl.create({
            title: "Error",
            subTitle: 'Mensajes: ' + data.error.tostring(),
            buttons: ["OK"]
          }).present();
        } else {
          //this.loading.dismissAll();
          //this.navCtrl.pop();
          this.resumen = data;
        }
      });
          
  }
}

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 'rxjs/add/observable/throw';
import { Observable } from 'rxjs/observable';
import * as jwt_decode from "jwt-decode";
import { HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage';

@Injectable()
export class ServiceRestProvider {

 // Token: any;
  token_full: 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_full != "") {
      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) => {
        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"];
          this.guardar_storage();
        }
      }, err => {      
        console.log(err);
      }
      );
  }

  private guardar_storage() {
    if (this.platform.is("cordova")) {
      this.storage.set('Token_Full', this.token_full);
    } else {
      if (this.token_full != "") {
        localStorage.setItem("Token_Full", this.token_full);
      } else {
        localStorage.removeItem("Token_Full");
      }
    }
  }

  cargar_storage() {
    let promesa = new Promise((resolve, reject) => {
      if (this.platform.is("cordova")) {
        this.storage.ready()
          .then(() => {
            this.storage.get("Token_Full")
              .then(Token => {
                console.log(Token);
                if (Token != "") {
                  this.token_full = Token;
                }
              })
          })
      } else {
        if (localStorage.getItem("Token_Full") !="") {
          this.token_full = localStorage.getItem("Token_Full");
        }
        resolve();
      }
    });
    return promesa;
  }

  getNovedades(FechaInicial: any, FechaFinal: any) {
    this.alertCtrl.create({
      title: "Token a enviar",
      subTitle: 'Mensajes: ' + localStorage.getItem("Token_Full").toString(),
      buttons: ["OK"]
    }).present();
    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);
      });
    });
  }

  getResumenMovimientos2() {
    this.alertCtrl.create({
      title: "Token a enviar",
      subTitle: 'Mensajes: ' + localStorage.getItem("Token_Full").toString(),
      buttons: ["OK"]
    }).present();

    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 this.http.get('http://intsdfca2:84/api/EstadoDeCuenta', { headers: header})
      .map((response) => {
          return response;
      }).catch(this.handleError);;
   
  }
  public handleError(error: HttpErrorResponse) {
    return Observable.throw(`Something bad happened; please try again later. error Info:  ${error.error.message}`);
  }
  Cerrar_Sesion() {
    this.token_full = null;
    this.guardar_storage();
  }
}

Image of the app in the browser:

Image of the app in cellphone:


#2

Dear, I think you have an erroneous concept to store the data on the device and what happened to clarify so you can better take your development. The problem you have is that you are storing the data in a storage variable that is to store the data in the storage of the browsers. to save the data on an android computer or ios you must install an add-on called firebase which I leave the link below:

Now with respect to the storage of the data that you need to rescue it, I will leave you a bit of the code of an application that I made in where I store this in the device

import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { SQLiteObject,  SQLite } from '@ionic-native/sqlite';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DatabaseServiceProvider {

  private database: SQLiteObject;
  private dbReady = new BehaviorSubject<boolean>(false);

  constructor(private platform:Platform, private sqlite:SQLite) {
    this.platform.ready().then(()=>{
      this.sqlite.create({
        name: 'prueba.db',
        location: 'default'
      })
      .then((db:SQLiteObject)=>{
        this.database = db;       
        this.createTable().then(()=>{     
          this.dbReady.next(true);
        });
      })
    });
  }

  private createTable() {
    return this.database.executeSql(`CREATE TABLE IF NOT EXISTS Sesion (
      id INTEGER,
      valor TEXT
      );`
    , [])
    .catch((err) =>
      console.log("error detected creating tables", err)
    );
  }

  private isReady() {
    return new Promise((resolve, reject) =>{
      if(this.dbReady.getValue()){
        resolve();
      }
      else{
        this.dbReady.subscribe((ready)=>{
          if(ready){ 
            resolve(); 
          }
        });
      }  
    })
  }

  getSesiones(){
    return this.isReady()
    .then(() => {
      return this.database.executeSql("SELECT * from Sesion", [])
      .then((data)=>{
        let lists = [];
        for(let i=0; i<data.rows.length; i++){
          lists.push(data.rows.item(i));
        }
        return lists;
      })
    })
  }

  addSesion(id:number, name:string){
    return this.isReady()
    .then(() => {
      return this.database.executeSql(`INSERT INTO Sesion(id, valor) VALUES ('${id}','${name}');`, [])
        .then((result)=>{
          if(result.insertId){
            return this.getSesion(result.insertId);
          }
        })
    });    
  }

  updateSesion(id:number, name:string){
    return this.isReady()
    .then(() => {
      return this.database.executeSql(`UPDATE Sesion SET valor='${name} WHERE id='${id}');`, [])
        .then((result)=>{
          if(result.insertId){
            return this.getSesion(result.insertId);
          }
        })
    });    
  }

  getSesion(id:number){
    return this.isReady()
    .then(() => {
      return this.database.executeSql(`SELECT * FROM Sesion WHERE id = ${id}`, [])
      .then((data)=>{
        if(data.rows.length){
          return data.rows.item(0);
        }
        return null;
      })
    })    
  }

  deleteSesion(id:number){
    return this.isReady()
    .then(()=>{
      return this.database.executeSql(`DELETE FROM Sesion WHERE id = ${id}`, [])
    })
  }

  GuardaSQLlite(id:number, valor:string)
  {
    //eliminando valor anterior
    this.deleteSesion(id)
    .then(result => {
      console.log('Data eliminada con exito')
    })
    .catch(error => {
      console.log("Error al eliminar data -> " + error);
    });

    //ingresando nuevo valor
    this.addSesion(id, valor)
    .then(result => {
      console.log('Data ingresada con exito')
    })
    .catch(error => {
      console.log("Error al guardar data -> " + error);
    });
  }
  
  EliminaSQLlite(id:number)
  {
    //eliminando valor anterior
    this.deleteSesion(id)
    .then(result => {
      console.log('Data eliminada con exito')
    })
    .catch(error => {
      console.log("Error al eliminar data -> " + error);
    });

  }

}


The code was created as a provider to be able to access this class from any part of the project if doing the corresponding import.

Now to store and rescue the data I leave the codes of my application as an example:

login(userInfo) {

    let url = `${this.url}/Login/login.php`;

    let data = { usuario : userInfo.user, clave: userInfo.clave};
    let token = this.GenerarToken(data);
    let body = {token: token};

    return new Promise((resolve, reject) => {
      this.nativeHttp.post(url, body, {})
        .then((result) => {

            var respuesta = JSON.parse(result.data);
            if (respuesta.status == "200") {
              let datosToken = JWT(respuesta.data);

              //guardando datos en el dispositivo
              this.databaseService.GuardaSQLlite(1, respuesta.data);  //Token Sesion
              this.databaseService.GuardaSQLlite(2, datosToken["prof_rut"]); //Rut
              this.databaseService.GuardaSQLlite(3, datosToken["prof_clave_liq"]); //Clave
              this.databaseService.GuardaSQLlite(4, datosToken["prof_nombre"] + " " + datosToken["prof_ape_paterno"] + " " + datosToken["prof_ape_materno"]); //Nombre
              this.databaseService.GuardaSQLlite(5, datosToken["prof_correo_corp"] + "|" + datosToken["prof_correo_cliente"] + "|" + datosToken["prof_email"]); //Correos
              this.databaseService.GuardaSQLlite(6, datosToken["cto_empresa"]); //Empresa
              this.databaseService.GuardaSQLlite(7, datosToken["CTO_ID"]); //Centro Costo

              resolve(true);

            } else {
              
              resolve(false); 

            }
         })
      .catch((error) => {
        console.log(error.error);
        reject(false);
      })
    });
 }

 logout(): void {
      this.databaseService.EliminaSQLlite(1);
      this.loggedIn = false;
  }

  isLoggedIn() {
      return this.loggedIn;
  }

Try to be as clear as possible but if you have any questions you can leave it in this post and I will try to answer it as soon as possible


#3

It looks like CORS may be the issue you are having. The headers you are setting should be set on the server. Check your debugging tools and see if a request of 200 fails. If so, CORS is the culprit.