如何将数据从工厂恢复到控制器 angularjs

how to recover data from factory to controller angularjs

我正在尝试从函数 regresarUsr() 的调用中恢复纯数据,我能够使用函数日志记录数据,但无法从函数 regresarUsr 内部将纯数据返回到控制器() 然后添加到 $scope.user 总是我 console.log() 来自控制器的数据未定义,但我需要实际对象。

app.factory('MGAindexdb', function(jsonService) {
    //
    // App global database instance and schema
    //
    var db = new Dexie("MGADT");
    db.version(1).stores({
        // friends: "++id,name,shoeSize",
        users: "++id,usr_id,nombre,email,fb_email,registration_date,validated,membership,amount,last_access,key,is_logged_in,imagenDeUsuario,total,meQueda,gastoDia",
        categories: "++id,category_id,user_id,nameCat,desc",
        expenses: "++id,exp_id,user_id,cat_id,amount,comments,date"
    });
    db.open();

    //
    // Populate some data
    //
    function populateUser(u, c, e) {

        log("Populating some populateUser", "heading");
        return db.transaction("rw", db.users, db.categories, db.expenses, function () {

            var cat;
            var exp;
            u = u.data;
            // console.log(u);
            db.users.clear();
            db.categories.clear();
            db.expenses.clear();

            var img = u.imagenDeUsuario.split('"')[7];
            console.log('Hola :DDD');
            db.users.add({ usr_id: u.user_id, nombre: u.name, email: u.email, fb_email: u.fb_email, registration_date: u.registration_date, validated: u.validated, membership: u.membership_type, amount: u.amount, last_access: u.last_access, key: u.key, is_logged_in: u.is_logged_in, imagenDeUsuario: img, total: u.total, meQueda: u.meQueda, gastoDia: u.gastoDia});

            var path = 'categories';
            var categories = jsonService.getjson( c, path, e).then(function(d) {
                cat = d.categories;
                angular.forEach(cat, function(c) { 
                    db.categories.add({category_id: c.category_id, user_id: c.user_id, nameCat: c.name, desc: c.description});
                });
            });

            var path = 'expenses';
            var expenses = jsonService.getjson( c, path, e).then(function(d) {
                exp = d.expenses;
                angular.forEach(exp, function(e) { 
                    db.expenses.add({ exp_id: e.expense_id, user_id: e.user_id, cat_id: e.category_id, amount: e.amount, comments: e.comments, date: e.date});
                });
            });

            // Log data from DB:
            // db.users.orderBy('nombre').each(function (user) {
            //     log(JSON.stringify(user));
            // });
            // db.categories.orderBy('nameCat').each(function (cate) {
            //     log(JSON.stringify(cate));
            // });
            // db.expenses.orderBy('exp_id').each(function (expe) {
            //     log(JSON.stringify(expe));
            // });
        }).catch(function (e) {
            log(e, "error");
            console.log('Error de populateUser');
        });
    }

    function regresarUsr () {
        log("Regresando Data de Usr", "heading");
        return db.transaction("rw", db.users, function () {
            db.users.orderBy('nombre').each(function (user) {
                // console.log(user);
                // log(JSON.stringify(user));
                // console.log(user);
                // alert(Dexie.getByKeyPath(users, "nombre")); // Will alert ("Kalle");
                return user;
            });

        }).catch(function (e) {
            log(e, "error");
            console.log('Error de regresarUsr');
        });
    }



    //
    // Helpers
    //
    function log(txt, clazz) {
        var li = document.createElement('li');
        li.textContent = txt.toString();
        if (clazz) li.className = clazz;
        document.getElementById('log').appendChild(li);
    }

    return {
       open: open,
       populateUser: populateUser,
       regresarCat: regresarCat,
       regresarExp: regresarExp,
       regresarUsr: regresarUsr,
       log: log

    };

// End
});

app.controller('DashboardCtrl', function($http, $scope, jsonService, sesionesControl, MGAindexdb) {

   $scope.user= function() {

      // console.log(MGAindexdb.regresarUsr());
      MGAindexdb.regresarUsr().then(function(data) {
        console.log(data);

      })
      .catch(function (e) {
        log(e, "error");
      });
    }
});

发生这种情况是因为您在从服务器 return 编辑 return 之前记录出厂值,因此它是未定义的。您必须使用承诺等到工厂实际包含数据。在 angular 中,您使用 $q 服务创建了一个承诺。

app.factory('MGAindexdb', function (jsonService, $q) {
    return {
        regresarUsr: function () {
            var deferred = $q.defer();

            db.transaction("rw", db.users, function () {
                db.users.orderBy('nombre').each(function (user) {
                    deferred.resolve(user);
                });

            }).
            catch (function (e) {
                deferred.reject(e);
            });
            return deferred.promise;
        }
    }
}

现在当你将$scope.user绑定到MGAindexdb.regresarUsr时,一个名为promise的占位符将被分配给$scope.user,它会在服务器请求[=25]时自动解析=]s.

编辑

自 angular 1.2 起,承诺在分配给范围变量时不会自动解析。所以你必须使用 Service.asyncCall().then(resolve promise here) 来手动解决承诺。