Search code examples
javascriptangularjscordovaionic-frameworkcordova-plugins

Ionic: TypeError: Cannot read property 'ready' of undefined


I am always getting this error: TypeError: Cannot read property 'ready' of undefined

This is my Code:

angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.directives','app.services', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
});
});

angular.module('app.services', [])
.service('DatabaseService', [function($cordovaSQLite, $ionicPlatform) {
    var db;

    $ionicPlatform.ready(function () {
    if(window.cordova) {
        db = $cordovaSQLite.openDB("auftragDB");    
    } else {
        db = window.openDatabase("auftragDB", "1.0", "Offline Artikel Datenbank", 10*1024*1024);
    }

    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS ArtikelTable (ticket_id number(10), kunde char(100))");
     });
}])

I have really no idea, why it seems to can't find the $ionicPlatform...

Best regards, Pearson


Solution

  • I think you should declare your service function like this

    angular.module('app.services', [])
    .service('DatabaseService', ['$cordovaSQLite', '$ionicPlatform', function($cordovaSQLite, $ionicPlatform) {
    
     // When you pass second argument of .service() as array, 
     // then the array should list all dependencies followed by function which use them 
    
    }])
    

    OR

    angular.module('app.services', [])
        .service('DatabaseService', function($cordovaSQLite, $ionicPlatform) {
    
         // or you can use a direct function with all dependencies as its parameter. 
         // But dependencies injection will break if you do code minification
    
        })
    

    Services can have their own dependencies. Just like declaring dependencies in a controller, you declare dependencies by specifying them in the service's factory function signature.

    Source: https://docs.angularjs.org/guide/services

    More: https://docs.angularjs.org/guide/di