使用模型和服务返回承诺

时间:2016-04-25 18:47:28

标签: javascript angularjs angular-promise q

我承诺错误。

我尝试使用angular-tree-dnd,但我的承诺存在问题。

来自我的控制器的

project.getAll().then(function(results) {
    var projects = results;

    $scope.results = [];

    angular.forEach(projects, function(result) {
        $scope.results.push(project.build(result));
    });

    return $scope.results;
});

$scope.tree_data = $TreeDnDConvert.line2tree($scope.results, 'id', 'ParentId');

我的模特:

var Project = function(properties) {
    // Model
    this.description = null;
    this.file = null;
    this.name = null;
    this.ParentId = null;
    this.path = null;

    angular.extend(this, properties);
};

Project.prototype.setModel = function(obj) {
    angular.extend(this, obj);
};

Project.prototype.getAll = function() {
    return ProjectService.getAll();
};

Project.prototype.build = function(data) {
    var project = new Project(data);

    return project;
};

我的服务(使用$ webSql):

this.getAll = function(params) {
    var projects = [];
    return db.selectAll('projects').then(function(results) {
        for (var i = 0; i < results.rows.length; i++) {
            projects.push(results.rows.item(i));
        }
        return projects;
    });
};

我没有错,但我的家是空的。

我试过了:

project.getAll().then(function(results) {
    var projects = results;

    $scope.results = [];

    angular.forEach(projects, function(result) {
        $scope.results.push(project.build(result));
    });

    return $scope.results;
}).then(function(array) {
    $scope.tree_data = $TreeDnDConvert.line2tree(array, 'id', 'ParentId');
});

但我有这个错误:

angular.min.js:13550 TypeError: Cannot read property '__children__' of undefined
    at Object._$initConvert.line2tree (ng-tree-dnd.js:1456)

我认为我的数组是空的

2 个答案:

答案 0 :(得分:1)

我怀疑这是你问题的根源:

"ParentId":"null"

树上的两个项目都有一个带有 字符串值 "null"的ParentId。这可能意味着dnd库正在寻找ID为"null"的节点,一无所获,并尝试访问该__children__值的undefined属性。

解决方案:修复数据库中的数据,使父ID实际上为空值,而不是值"null"

答案 1 :(得分:0)

晚上好) 请设置一个断点,或者在上一次操作之前使用debuggeralertconsole.logJSON.stringify(array)

$scope.tree_data = $TreeDnDConvert.line2tree(array, 'id', 'ParentId') 

(带有then和错误的最新版本)。

我认为你有正确的数组,而不是在promises中,而是在line2tree语法中。