ионные необученные (в обещании): [объект: объект] - PullRequest
1 голос
/ 20 марта 2019

Я пытаюсь заполнить некоторые таблицы при создании базы данных в Ionic v3.Есть таблица валют, все валюты сохранены в файле JSON.Также есть таблица настроек.Я хочу установить все настройки на их значения по умолчанию при создании БД.Итак, вот мой код:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { ObjBkpr } from "../../shared/ObjBkpr";

@Injectable()
export class DbApi {
  public db: SQLiteObject;

  static readonly dbName = 'ebookiper_a45fed6.db';
  static readonly dbLocation = 'default';

  currenciesURL = 'assets/files/currencies.json';
  currenciesData:any;

  constructor(public http: HttpClient, private sqlite: SQLite) {
  }

  /** CREATE DATABASE AND TABLES IF NOT EXIST. ALSO INSERT ALL CURRENCIES IN TABLE */
  createDatabase(){
    return this.sqlite.create({ name: DbApi.dbName, location: DbApi.dbLocation }).then((db:SQLiteObject) => {
      this.db = db;
        return this.db.executeSql(DbApi.createTableTrans, []).then(data => {
          return this.db.executeSql(DbApi.createTableCat, []). then(data => {
            return this.db.executeSql(DbApi.createTableCredit, []). then(data => {
              return this.db.executeSql(DbApi.createTableAcc, []). then(data => {
                return this.db.executeSql(DbApi.createTableSetting, []). then(data => {
                  return this.db.executeSql(DbApi.createTableCurr, []). then(data => {
                    this.populateCurrencies();
                    this.populateSettings();
                  });
                });
              });
            });
          });
        });
    });
  }


  populateCurrencies(){
    // Find if there are already records in the table
    let sqlQuery = ' SELECT COUNT(*) AS total FROM ' + DbApi.tableCurrency + ';';
    return this.sqlite.create({ name: DbApi.dbName, location: DbApi.dbLocation }).then((db:SQLiteObject) => {
      return db.executeSql(sqlQuery, []).then(data =>{
        if (data.rows.length > 0) {
          if(data.rows.item(0).total == 0){
            this.getCurrencies();
          }
        }
      });
    });
  }

  getCurrencies(){
    this.http.get(this.currenciesURL)
      .map(res => {
        this.currenciesData = res;
        let total = this.currenciesData.length;
        if( total > 0){
          for(var i=0; i<total; i++){
            let item = this.currenciesData[i];
            let cur = new ObjBkpr();
            cur.designation = item.Code;
            cur.notes = item.Country + ' [' + item.Currency + '] ';
            this.insert(DbApi.tableCurrency, cur);
          }
        }
      }).subscribe(data => {
        // we've got back the raw data
      });
  }

  populateSettings(){
    // Find if there are already records in the table
    let sqlQuery = ' SELECT COUNT(*) AS total FROM ' + DbApi.tableSetting + ';';
    this.sqlite.create({ name: DbApi.dbName, location: DbApi.dbLocation }).then((db:SQLiteObject) => {
      db.executeSql(sqlQuery, []).then(data =>{
        if (data.rows.length > 0) {
          if(data.rows.item(0).total == 0){
            let defaultSettings = [ {key:DbApi.settingPassword,   value:''},
                                    {key:DbApi.settingQuestion1,  value:''},
                                    {key:DbApi.settingQuestion2,  value:''},
                                    {key:DbApi.settingAnswer1,    value:''},
                                    {key:DbApi.settingAnswer2,    value:''},
                                    {key:DbApi.settingPageItems,  value:'50'}, ];
            let nbItems = defaultSettings.length;
            let setting = new ObjBkpr();
            for(var i=0; i<nbItems; i++){
              setting.keyS   = defaultSettings[i].key;
              setting.valueS = defaultSettings[i].value;
              this.insert(DbApi.tableSetting, setting);
            }
          }
        }
      }).catch(e=>{
        console.log('POPULATE SETTINGS: ' + e.message);
      });
    });
  }
}

Обратите внимание на строки

this.populateCurrencies();
this.populateSettings();

Первый работает нормально.Но второе дает мне ошибку, Uncaught (в обещании): [object: object] Что не так с кодом?Как работают обещания при использовании .map() или .then() точно

...