[AngularJS]角"这种"符号和数据服务与承诺

发布时间: 2017/4/16 20:23:05
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

所以,让我们削减的情况。我有以下服务︰

feedBackModule.factory("feedbackSkillService", function ($q, $filter, Query) {
    var skills = [];
    return {
        getSkills: function () {
            var d = $q.defer();
            if (skills.length <= 0) {
                Query.api2({
                    method: 'GET',
                    route: 'feedback/skill'
                }).then(function (result) {
                    skills = result;
                    d.resolve(result);
                });
            }
            else {
                d.resolve(skills);
            }
            return d.promise;
        },
        putSkill: function (skill) {
            skills.push(skill);
        },
        deleteSkill: function (skill) {
            var index = skills.indexOf(skill);
            Query.api2({
                method: 'DELETE',
                route: 'feedback/skill',
                params: {id: skill.id}
            });
            skills.splice(index, 1);
        },
        editSkill: function (skill) {
            Query.api2({
                method: 'PUT',
                route: 'feedback/skill',
                params: {id: skill.id},
                data: {skill: skill}
            });
        }
    }

});

及以下 controller :

    feedBackModule.controller('createCollectionController', ['Query', '$modalInstance', 'feedbackSkillService', 'feedbackCollectionService', function (Query, $modalInstance, feedbackSkillService, feedbackCollectionService) {
    this.collection = {};
    this.skills = [];

    feedbackSkillService.getSkills().then(function (result) {
        this.skills = result;
    });

    this.createSkill = function () {
        Query.api2({
            method: 'POST',
            route: 'feedback/skill',
            data: {skill: this.skill}
        }).then(function (result) {
            feedbackSkillService.putSkill(result);
        });
        $modalInstance.dismiss('cancel');
    };

    this.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]);

正如你可以看到我想取从技能feedbackSkillService

但是因为这一次使用承诺它返回 this.skill 是意味着不能访问它,并且正确设置的范围之外。我知道你能做这与 $scope 但我不想使用 $scope

那么如何确保我可以访问该变量?

解决方法 1:

feedbackSkillService.getSkills().then(function (result) {
    this.skills = result;
}.bind(this));
// ^^^^^^^^

您只需确保 this 里面回调仍指 this 你期望; 最简单的办法在这里是 bind 回调函数的上下文。

请注意,你可能还有异步时序问题,并且的时候你调用 this.createSkill result 可能不还没有回来。

赞助商