角承诺的'then'函数的成功回调的词法范围是什么?



我试图理解为什么在我的控制器中注入(或声明的其他变量)中的某些依赖项在延迟承诺的"then"函数的成功/错误回调中不可用。

我已经搜索了角度$q的文档和这里的几个帖子,但我无法回答我的问题......也许我没有搜索正确的关键字,我不知道。

这是我的控制器的片段,其中包含我想知道的问题。提前感谢!

(function () {
'use strict';
angular
    .module('app.aModule')
    .controller('mycontroller', MyController);
MyController.$inject = ['$controller', '$scope', 'myService'];
function MyController($controller, $scope, myService) {
    $scope.myProp;
    var myVariable1 = 'hello';
    //.............some code.................
    $scope.save = function(event) {
            var myVariable2 = 'World!';
            myService.post($scope.myProp).then(
                function (result) {
                    // 1. can I access to myVariable1 here?
                    // 2. can I access to myVariable2 here?
                    // 3. can I access to $scope or $controller dependency here?
                    // 4. can I access to myService dependency here?
                },
                function (error) {
                    // do something
                }
            );
        };
    //.............some code.................
}
})();

这是我的角度服务的发布方法:

 function post(data) {
        var deferred;
        deferred = $q.defer();
        $http.post(apiUrl + endpoint + 'post', data).then(function (result) {
            deferred.resolve(result);
        }, function (error) {
            deferred.reject(error);
        });
        return deferred.promise;
    };

它不依赖于承诺。你无法理解闭包功能。

闭包是一个可以访问父作用域(它不是角度作用域)的函数,即使在父函数关闭之后也是如此。如果你将 myVariable1 或(和)myVariable2 写入函数,则可以看到这种变化,但如果你只是调试它,你就看不到它(如果你没有写它)。

答案:1 和 2 - 取决于您如何做到这一点。3. $scope - 是的。控制器 - 无法理解是什么意思。4. 与 1 和 2 的答案相同。

最新更新