Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48983

Ionic android app is not getting data

$
0
0

Hi guys, I need some advice, we are going to build android application with Ionic, we built our app, it worked well on web, but after building Android app we faced some issues.

In our android app we couldn’t get data.

This is store service code, components get data from store services behavior subjects .

import {EventEmitter, Injectable, NgZone} from '@angular/core';
import {ApiService} from './api.service';
import {BehaviorSubject} from 'rxjs';
import {Device} from './models/device';
import {GHReadingsCollection} from './models/gh-reading';
import {MeteoReadingsCollection} from './models/meteostation-reading';
import {Settings} from './models/settings';
import {GasIndicators} from './models/gas-indicators';

@Injectable({
  providedIn: 'root'
})
export class StoreService {
  public devices = new BehaviorSubject<Device[]>([]);
  public isGasOn = new BehaviorSubject<boolean>(false);
  public period = new BehaviorSubject<string>('-24h');
  public ghReadings = new BehaviorSubject<GHReadingsCollection>({});
  public meteoReadings = new BehaviorSubject<MeteoReadingsCollection>({});
  public settings = new BehaviorSubject<Settings>(null);
  public masterDevice = new BehaviorSubject<Device>(null);
  public gasIndicators = new BehaviorSubject<GasIndicators>(null);
  public mapGhReadings = new BehaviorSubject<GHReadingsCollection>({});

  public reloadStarted = new EventEmitter();
  public reloadEnded = new EventEmitter();
  public reloadCalled = new EventEmitter();

  constructor(private apiSvc: ApiService, private zone: NgZone) {
  }

  public async reload(period: string): Promise<void> {
    try {
      this.reloadStarted.emit();

      const devices = await this.apiSvc.getDevices();
      const ghReadings: GHReadingsCollection = await this.apiSvc.getGHReadingCollection(devices, period);
      const meteoReadings: MeteoReadingsCollection = await this.apiSvc.getMeteoReadingCollection(devices, period);
      const gasReading: GasIndicators = await this.apiSvc.getGasReading(period, 'now()');

      this.devices.next(devices);
      this.ghReadings.next(ghReadings);
      this.meteoReadings.next(meteoReadings);
      this.gasIndicators.next(gasReading);
      this.period.next(period);

      await this.reloadMapData(devices);
    } catch (e) {
      console.error(e);
    } finally {
      this.reloadEnded.emit();
    }
  }

  public async reloadSettings(): Promise<void> {
    const devices = await this.apiSvc.getDevices();
    for (const d of devices) {
      const setts: Settings = JSON.parse(d.settings);
      if (setts && setts.isMaster) {
        this.settings.next(setts);
        this.masterDevice.next(d);
        break;
      }
    }
  }

  public async reloadMapData(devices) {
    const mapGhReadings: GHReadingsCollection = await this.apiSvc.getGHReadingCollection(devices, '-15m');
    const mapMeteoReadings: MeteoReadingsCollection = await this.apiSvc.getMeteoReadingCollection(devices, '-15m');
    const isGasOn: boolean = this.apiSvc.getIsGasOn(mapMeteoReadings);

    this.mapGhReadings.next(mapGhReadings);
    this.isGasOn.next(isGasOn);
  }


}

After some research I found out we have to get data from Promise via .then() method in Ionic.
After implementing this idea I got devices data in Android app but not ghReadings, meteoReadings and gasIndicators.

This is our api service code, we get ghReadings, meteoReadings and gasIndicators with post methods.

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Device} from './models/device';
import {GHReading, GHReadingRequest, GHReadingsCollection} from './models/gh-reading';
import {MeteoReading, MeteoReadingRequest, MeteoReadingsCollection} from './models/meteostation-reading';
import {environment} from '../environments/environment';
import {ApiResponse} from './models/api-response';
import {GasIndicators, GasIndicatorsRequest} from './models/gas-indicators';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  public constructor(private http: HttpClient) {
  }

  public async getDevices(): Promise<Device[]> {
    const resp = await this.http.get<ApiResponse<Device[]>>(environment.buildUrl('user/devices')).toPromise();
    return resp.data;
  }

  public async getGHReadingCollection(devices: Device[], period): Promise<GHReadingsCollection> {
    const ghReadings: GHReadingsCollection = {};
    const interval = this.getIntervalByPeriod(period);
    for (const d of devices) {
      if (d.device_type === 'GH station') {
        ghReadings[d.serial_number] = await this.getGHReadings(d.serial_number, period, 'now()', interval);
      }
    }
    return ghReadings;
  }

  public async getMeteoReadingCollection(devices: Device[], period): Promise<MeteoReadingsCollection> {
    const meteoReadings: MeteoReadingsCollection = {};
    const interval = this.getIntervalByPeriod(period);
    for (const d of devices) {
      if (d.device_type === 'Meteostation') {
        meteoReadings[d.serial_number] = await this.getMeteoReadings(d.serial_number, period, 'now()', interval);
      }
    }
    return meteoReadings;
  }

  public getIsGasOn(readings: MeteoReadingsCollection): boolean {
    for (const d in readings) {
      const last = readings[d].length - 1;
      if (last > 0 && 'Gas' in readings[d][last]) {
        return readings[d][last].Gas === 1;
      }
    }
    return false;
  }

  public async getGHReadings(id: string, start: string, end: string, interval: string): Promise<GHReading[]> {
    const req: GHReadingRequest = {
      stationId: id,
      start,
      end,
      interval
    };

    const httpOptions = {
      headers: new HttpHeaders({
        // eslint-disable-next-line @typescript-eslint/naming-convention
        'Content-Type': 'application/json',
      })
    };
    const resp = await this.http.post<ApiResponse<GHReading[]>>(environment.buildUrl('influx/greenhouse'), req, httpOptions).toPromise();
    return resp.data;
  }

  public async getMeteoReadings(id: string, start: string, end: string, interval: string): Promise<MeteoReading[]> {
    const req: MeteoReadingRequest = {
      stationId: id,
      start,
      end,
      interval
    };

    const httpOptions = {
      headers: new HttpHeaders({
        // eslint-disable-next-line @typescript-eslint/naming-convention
        'Content-Type': 'application/json',
      })
    };
    // eslint-disable-next-line max-len
    const resp = await this.http.post<ApiResponse<MeteoReading[]>>(environment.buildUrl('influx/meteostation'), req, httpOptions).toPromise();
    return resp.data;
  }

  public async getGasReading(start: string, end: string): Promise<GasIndicators> {
    const req: GasIndicatorsRequest = {
      start: this.convertRelativeDateToAbsolute(start),
      end: this.convertRelativeDateToAbsolute(end)
    };

    const httpOptions = {
      headers: new HttpHeaders({
        // eslint-disable-next-line @typescript-eslint/naming-convention
        'Content-Type': 'application/json',
      })
    };
    const resp = await this.http.post<ApiResponse<GasIndicators>>(environment.buildUrl('influx/gas'), req, httpOptions).toPromise();
    return resp.data;
  }


  public async saveDeviceSettings(serialNumber: string, settings: string): Promise<{ success: boolean }> {
    const req = {
      // eslint-disable-next-line @typescript-eslint/naming-convention
      serial_number: serialNumber,
      settings
    };
    const httpOptions = {
      headers: new HttpHeaders({
        // eslint-disable-next-line @typescript-eslint/naming-convention
        'Content-Type': 'application/json',
      })
    };
    const resp = await this.http.post<{ success: boolean }>(environment.buildUrl('user/updateDeviceSettings'), req, httpOptions).toPromise();
    return resp;
  }

  private convertRelativeDateToAbsolute(d: string): string {
    let curDate = new Date();
    switch (d) {
      case '-3d':
        curDate = new Date((new Date()).getTime() - 1000 * 60 * 60 * 24 * 3);
        break;
      case '-24h':
        curDate = new Date((new Date()).getTime() - 1000 * 60 * 60 * 24);
        break;
      case '-12h':
        curDate = new Date((new Date()).getTime() - 1000 * 60 * 60 * 12);
        break;
      case '-6h':
        curDate = new Date((new Date()).getTime() - 1000 * 60 * 60 * 6);
        break;
      case '-3h':
        curDate = new Date((new Date()).getTime() - 1000 * 60 * 60 * 3);
        break;
    }

    return curDate.toISOString();
  }

  private getIntervalByPeriod(period: string): string {
    const intervalByPeriod = {
      '-3h': '15m',
      '-6h': '15m',
      '-12h': '30m',
      '-24h': '30m',
      '-3d': '1h'
    };

    return intervalByPeriod[period];
  }

}

Questions:

  1. Is getting and returning data as Promise good idea ? Or should we use Observables ? Does this have any effect on the performance of the android app ?
  2. What could be the reason of not getting data(ghReadings, meteoReadings and gasIndicators) on android app and how to fix it ?
  3. I found Ionic have its own http library , will using this library solve our issue ? do we have to use this library for our http requests to work well?

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 48983

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>