I am using ionic framework .
I am implementing following steps
1) As my app runs . it will create db and table 2) As soon as use login, i am saving data into mysql and go to Dashboard page
dbQuery.insertCategory();
$state.go('app.dashboard');
dbQuery is factory .
.factory('dbQuery', function ($http, $q, $cordovaSQLite, localstorage) {
return {
insertCategory: function () {
$http({
url: "http://mydoman.comcategory",
method: 'GET',
withCredentials: true,
}).success((function (result) {
var user_id = localstorage.get('user_id');
var query = "INSERT OR IGNORE INTO categories (category_id, user_id, category_name,category_type) VALUES (?,?,?,?)";
var data = '';
result.forEach(function (category) {
$cordovaSQLite.execute(db, query, [category.id,user_id, category.category_name, category.category_type]).then(function (res) {
console.log("insertId");
}, function (err) {
console.dir(err);
});
});
}))
},
Which is working fine
On Dashboard i am showing categories list and i found nothing .
I did debugging and found insertion of categories taking time to insert.
Is there is any way to do two way data binding
Thanks
Why not use a promise and only redirect to app.dashboard
once the success promise triggers?
Example:
dbQuery.insertCategory().then(function(result) {
$state.go('app.dashboard');
}, function(error) {
console.error(error);
});
Then in your factory you can have something like this:
.factory('dbQuery', function ($http, $q, $cordovaSQLite, localstorage) {
return {
insertCategory: function () {
var deferred = $q.defer();
$http({
url: "http://mydoman.comcategory",
method: 'GET',
withCredentials: true,
}).success((function (result) {
var user_id = localstorage.get('user_id');
var query = "INSERT OR IGNORE INTO categories (category_id, user_id, category_name,category_type) VALUES (?,?,?,?)";
var data = '';
result.forEach(function (category) {
isWaiting = true;
$cordovaSQLite.execute(db, query, [category.id,user_id, category.category_name, category.category_type]).then(function (res) {
console.log("insertId");
isWaiting = false;
}, function (err) {
console.dir(err);
isWaiting = false;
});
while(isWaiting) {}
});
deferred.resolve("done");
}))
return deferred.promise;
},
A lot of what I did is just theory, but it should give you an idea. I created a boolean to make the SQL commands synchronous. Since they are synchronous, when the loop ends, you can return your success promise.
There are probably a few other ways you could do it as well. Like maybe move the SQL stuff into its own function and recursively enter it.
Let me know if any of this works for you.