I have service which has asynchronous init of parameter and I want that every controller to wait until the init will be finished.
The problem is that the getObject method is being called by the controller before the init of parameters variable is finished.
The service:
angular.module('core')
.factory('localstorage', ['$window', '$cordovaSQLite', '$q',
function ($window, $cordovaSQLite, $q) {
var db;
var parameters = {};
if (window.cordova) {
db = $cordovaSQLite.openDB({name: "my.db"}); //device
} else {
db = window.openDatabase("my.db", '1', 'life', 1024 * 1024 * 100);
}
var promise = $q(function (resolve, reject) {
$cordovaSQLite.execute(db, "SELECT * FROM life_table")
.then(function (res) {
if (res.rows.length == 0) {
$cordovaSQLite.execute(db,
"CREATE TABLE IF NOT EXISTS life_table (key text primary key, value text)");
}
else {
for (var i = 0; i < res.rows.length; ++i) {
parameters[res.rows[i].key] = JSON.parse(res.rows[i].value);
}
}
resolve(parameters);
});
});
return {
promise: promise,
getObject: function (key) {
var query = "SELECT value FROM life_table where key = ?";
$cordovaSQLite.execute(db, query, [key]).then(function (res) {
if (res.rows.length > 0) {
console.log("getObject: " + res.rows[0].value);
}
}, function (err) {
console.error(err);
});
return parameters[key];
}
}
}]);
the config:
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('navigator', {
url: '/',
abstract: true,
controller: 'NavigatorCtrl',
resolve: {
'MyServiceData': function (localstorage) {
// localstorage will also be injectable in the controller
return localstorage.promise;
}
}
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl',
controllerAs: 'loginCtrl',
resolve: {
'MyServiceData': function (localstorage) {
// localstorage will also be injectable in the controller
return localstorage.promise;
}
}
})
Shalom Dor!
Option 1
Make a chain of promises and return the factory only after all promises are resolved. This will prevent the controller from running as the factory dependency will not be returned until the desired promises are resolved.
Option 2
Create some sort initialization function in your service that returns a promise (you can use $q). Execute it inside $ionicPlaform.ready() and only run the controller logic after you got the promise.
In the controller:
MyService.initialize().then(function () {
// Service initialized, do stuff...
});
In the service:
returned.initialize = function () {
var d = q.defer();
// Do stuff...
// Resolve 'd' when you finished initializing the service using 'd.resolve()'.
return d.promise;
};
Related
This is my first class where I defined all db functions.
import React,{Component} from 'react';
var Datastore = require('react-native-local-mongodb')
, db = new Datastore({ filename: 'asyncStorageKey', autoload: true });
export default class RDDBManager {
static dbmanager = null;
static getInstance() {
if (RDDBManager.dbmanager == null) {
RDDBManager.dbmanager = new RDDBManager();
}
return this.dbmanager;
}
constructor () {
}
//insert items
insertItem(item){
var json = item.toJsonString();
console.log("Inside insertItem ::: "+json);
db.insert(json,function(err,newDos){
return newDos;
});
}
//read single item
readItem(itemId){
db.findOne({ id: itemId }, function (err, doc) {
return doc;
});
}
//read all items
readAllItems(){
db.find({}, function (err, docs) {
return docs;
});
}
getModalData(modalName) {
this.readAllItems();
}
//update
updateItem(itemId){
db.update({ id: itemId }, { $set: { system: 'solar system' } }, { multi: true }, function (err, numReplaced) {
});
}
//delete item
deleteItem(itemId){
db.remove({ id: itemId }, {}, function (err, numRemoved) {
return numRemoved;
});
}
}
But,when I try to call these functions from another class,the data is undefined.
loadDataFromDB() {
var items = RDDBManager.getInstance().readAllItems();
console.log("Items ======>>>>>> "+items);
}
the value of items is undefined.
This is because you are not doing things right, Your readallitems is async in nature so you have to do something like this:-
//read all items
readAllItems(callback){
db.find({}, function (err, docs) {
callback(docs);
});
}
And For calling something like this:-
loadDataFromDB() {
RDDBManager.getInstance().readAllItems(function(items){
console.log("Items ======>>>>>> "+items);
});
}
Alternatively, you can use promise or Async await also.
I currently have this code:
// Imports
const {utils: Cu, Constructor: CC} = Components;
Cu.import('resource://gre/modules/Services.jsm');
Services.scriptloader.loadSubScript('chrome://trigger/content/webextension/scripts/3rd/polyfill.min.js');
function install() {}
function uninstall() {}
function shutdown() {}
function startup() { // this gets automatically called by the environment i am designing for
Services.prompt.alert(Services.wm.getMostRecentWindow('navigator:browser'), 'title', 'body');
}
async function doAsync() {
return await new Promise(() => setTimeout(()=>resolve('done'), 5000));
}
However after compiling with babel with this .babelrc:
{
"presets": ["es2015", "es2017"],
"plugins": ["transform-object-rest-spread"],
"ignore": [
"3rd/**/*",
]
}
It moves my doAsync function to the top. Before the imports. Which is a problem. Because the import needs to happen right away. As startup gets called right away.
The compiled code becomes this:
'use strict';
var doAsync = function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return new Promise(function () {
return setTimeout(function () {
return resolve('done');
}, 5000);
});
case 2:
return _context.abrupt('return', _context.sent);
case 3:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function doAsync() {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
// Imports
var _Components = Components,
Cu = _Components.utils,
CC = _Components.Constructor;
Cu.import('resource://gre/modules/Services.jsm');
Services.scriptloader.loadSubScript('chrome://trigger/content/webextension/scripts/3rd/polyfill.min.js');
function install() {}
function uninstall() {}
function shutdown() {}
function startup() {
// this gets automatically called by the environment i am designing for Services.prompt.alert(Services.wm.getMostRecentWindow('navigator:browser'), 'title', 'body');
}
Is there anyway so that if I use async/await that it doesn't move stuff to above my imports? If my imports at the top of the file, it fails to run. Because the imports brings in the polyfill.min.js
I have used service for storing data in local storage using pouchDB. I would like to show ionic loading until the data are downloaded and stored locally. For now I have used timeout which is not an option for me.
My Service
function populateLocaldb() {
var count;
_localdb.info().then(function(d){
console.log(d.doc_count)
count = d.doc_count;
if(count===0) {
populateData1();
populateData2();
populateData3();
} else {
}
});
}
function populateChapter() {
$http.get('http://....').success(function(data) {
//console.log(data)
var values= data;
for(var i=0; i<values.length; i++) {
var value= {
_id: values[i].ID,
title: chapters[i].Title
}
_localdb.put(value, function callback(err, result) {
if (!err) {
console.log('Successfully posted a value!');
}
});
}
})
}
Controller
dbService.getAllinfo().then(function(data) {
if(data == ""){
//do nothing
//alert(" null Alert hello")
console.log(data)
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
}).then(function() {
dbService.populateLocaldb();
});
} else {
//do nothing
}
})
$timeout(function () {
$ionicLoading.hide();
}, 50000);
It looks like you might need to call $scope.$apply() in the PouchDB callback. Also, another tip: instead of doing multiple put()s inside of a forEach(), it's more efficient in PouchDB to do a single bulkDocs() operation.
My problem is, that the controller just send an undefiend and not the data from http of service. I inspect it with chrome. I am new at ionic. By calling the AppSqliDBFactory.getMasterdataId() method, it shows an undefiend, also at the scope variable.
.controller('ReadMasterdataCtrl', function ($scope, $state, $ionicNavBarDelegate, MasterdataService, AppSqliDBFactory){
$scope.masterdataId;
$scope.masterdataData;
AppSqliDBFactory.getMasterdataId().then( function (masterdata){
$scope.masterdataId = masterdata[0].masterdataId;
}).catch(function (err){
console.log(err);
});
//here is the error -> no data at "$scope.masterdataData = masterdata;"
MasterdataService.getMasterdataDB($scope.masterdataId)
.then(function (masterdata) {
$scope.masterdataData = masterdata;
console.log("getMasterdataDB respont");
console.log($scope.masterdataData);
}).catch(function (err) {
console.log(err);
});
})
//Service
.factory('MasterdataService', function ($q, $http, SERVER_URL) {
//Create JSON Object
var srv = {};
//Array for JSON Objects
srv.masterdata = [];
srv.getMasterdataDB = function (masterdataId) {
var deferred = $q.defer();
var masterdata;
var masterdataId = masterdataId;
var baseUrl = 'xxxx';
$http.get(SERVER_URL + baseUrl + masterdataId).success(function (response){
masterdata = response[0];
console.log(masterdata);
return deferred.resolve(masterdata);
}).error(function (err){
return deferred.reject(err);
});
return deferred.promise;
//return srv.getMasterdata();
};
// Public API
return {
getMasterdataDB: function ( masterdataId) {
return $q.when(srv.getMasterdataDB( masterdataId));
}
};
});
Simplified:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
});
MasterdataService.getMasterdataDB($scope.masterdataId).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
When MasterdataService.getMasterdataDB() is called, AppSqliDBFactory.getMasterdataId() may not have been resolved yet, so $scope.masterdataId can be undefined (which is probably what is happening in your case).
You have to call AppSqliDBFactory.getMasterdataId() after AppSqliDBFactory.getMasterdataId() has been resolved:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
MasterdataService.getMasterdataDB($scope.masterdataId).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
});
Or with chaining:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
return MasterdataService.getMasterdataDB($scope.masterdataId);
}).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
I have developed an OpenUI5 app ant it works fine!
But every time that I invoke the routing I have this message:
2015-07-15 16:15:45 hash format error! The current Hash: /line/01 -
log
error
onHashChange
detectHashChange
jQuery.event.dispatch
jQuery.event.add.elemData.handle
It is not a blocking problem but it is annoying because it dirty and fills thi debug console..!
To call the router I write:
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("activities", {
"id_line": '01'
});
and this is the routing file:
routes: [
...
{
pattern: "line/{id_line}",
name: "activities",
target: ["master_search", "detail_activities"]
},
...
],
targets: {
master_search: {
viewName: "UniversalMenu",
viewLevel: 1,
controlAggregation: "masterPages"
}
,
detail_activities: {
viewName: "DetailActivity",
viewLevel: 4
}
...
}
Edit: this is a snippet where I use jQuery.sap.history
jQuery.sap.require("jquery.sap.history");
jQuery.sap.require("sap.m.InstanceManager");
sap.ui.controller("ui5bp.view.App", {
getDefaultPage : function () {
return "Menu";
},
onInit : function () {
var historyDefaultHandler = function (navType) {
if (navType === jQuery.sap.history.NavType.Back) {
//this.navBack(this.getDefaultPage());
} else {
this.navTo(this.getDefaultPage(), null, false);
}
};
var historyPageHandler = function (params, navType) {
if (!params || !params.id) {
jQuery.sap.log.error("invalid parameter: " + params);
} else {
if (navType === jQuery.sap.history.NavType.Back) {
this.navBack(params.id);
} else {
this.navTo(params.id, params.data, false);
}
}
};
jQuery.sap.history({
routes: [{
// This handler is executed when you navigate back to the history state on the path "page"
path : "page",
handler : jQuery.proxy(historyPageHandler, this)
}],
// The default handler is executed when you navigate back to the history state with an empty hash
defaultHandler: jQuery.proxy(historyDefaultHandler, this)
});
// subscribe to event bus
var bus = sap.ui.getCore().getEventBus();
bus.subscribe("nav", "to", this.navHandler, this);
bus.subscribe("nav", "back", this.navHandler, this);
bus.subscribe("nav", "virtual", this.navHandler, this);
},
navHandler: function (channelId, eventId, data) {
if (eventId === "to") {
this.navTo(data.id, data.data, true);
} else if (eventId === "back") {
//**************************************************
// if(data && data.id){
// this.navBack(data.id);
// } else {
// jQuery.sap.history.back();
// }
var app = this.getView().app;
if(data.type==="master"){
app.backMaster();
}else if(data.type==="detail"){
app.backDetail();
}else{alert("back to master o detail?");};
//**************************************************
} else if (eventId === "virtual") {
jQuery.sap.history.addVirtualHistory();
} else {
jQuery.sap.log.error("'nav' event cannot be processed. There's no handler registered for event with id: " + eventId);
}
},
navTo : function (id, data, writeHistory) {
if (id === undefined) {
// invalid parameter
jQuery.sap.log.error("navTo failed due to missing id");
} else {
var app = this.getView().app;
// navigate in the app control
app.to(id, "slide", data);
}
},
/*
navBack : function (id) {
if (!id) {
// invalid parameter
jQuery.sap.log.error("navBack - parameters id must be given");
} else {
// close open popovers
if (sap.m.InstanceManager.hasOpenPopover()) {
sap.m.InstanceManager.closeAllPopovers();
}
// close open dialogs
if (sap.m.InstanceManager.hasOpenDialog()) {
sap.m.InstanceManager.closeAllDialogs();
jQuery.sap.log.info("navBack - closed dialog(s)");
}
// ... and navigate back
var app = this.getView().app;
var currentId = (app.getCurrentPage()) ? app.getCurrentPage().getId() : null;
if (currentId !== id) {
app.backToPage(id);
jQuery.sap.log.info("navBack - back to page: " + id);
}
}
}
*/
});
In Component.js I had 2 rows where I set up custom myNavBack and myNavToWithoutHash functions:
// 3a. monkey patch the router
var oRouter = this.getRouter();
oRouter.myNavBack = ui5bp.MyRouter.myNavBack; //to comment
oRouter.myNavToWithoutHash = ui5bp.MyRouter.myNavToWithoutHash; //to comment
I have started from an example of app skeleton for my app and then I have implemented the routing with the logic suggested from the framework.
This coexistence of two different methods to navigate produced the error in console. Tahnkyou #TimGerlach
After the comment of the two rows errors have vanished.