构造函数中的Http请求不会更改属性值

时间:2016-01-03 18:17:38

标签: angularjs

我遇到了这个构造函数的问题:

 function ApiManager() {
    this.api= new ApiInterface();
    this.apiVersion = -1;

    this.api.getVersion()
        .then(function(version) {
            console.log(version); // "1.0"
            this.apiVersion = version;
            console.log(this.apiVersion); // "1.0"
        }, function(error) {
            console.log("Couldn't find API version.")
        });
}
ApiManager.prototype = {
    getApiVersion: function() {
        return this.apiVersion; // "-1"
    }
};

我有一个带有属性apiVersion的对象,它使用值-1初始化。之后,ApiInterface执行HTTP请求,并为apiVersion分配值1.0。后来我调用函数getApiVersion并返回旧值-1。

我是AngularJS的新手,可能是一个愚蠢的菜鸟错误,但我看不出我的错误。

2 个答案:

答案 0 :(得分:0)

这是Promises / A + Spec对this函数中.then关键字的说法:

  

也就是说,在严格模式下,this将在其中undefined;在草率模式下,它将成为全局对象。

- Promises/A+ Spec -- Note 3.2

因此,在您的代码中,您需要显式绑定而不是使用this关键字。

function ApiManager() {
    this.api= new ApiInterface();
    this.apiVersion = -1;

    //bind 'this' keyword to a var
    var vm = this;

    this.api.getVersion()
        .then(function(version) {
            console.log(version); // "1.0"
            //use that binding
            vm.apiVersion = version;
            console.log(vm.apiVersion); // "1.0"
        }, function(error) {
            console.log("Couldn't find API version.")
        });
}

答案 1 :(得分:0)

我也尝试了带有诺言的版本,这就是结果:

function ApiManager() {
    this.api= new ApiInterface();
    this.apiVersion = api.getVersion();
}

ApiManager.prototype = {
    getApiVersion: function() {
        return this.apiVersion;
    }
};

ApiInterface在getVersion方法中返回一个promise。

getVersion: function() {
        return $http({
            method: 'GET',
            url: myUrl;
        }).then(function successCallback(response) {
            return response.data.jsonapi.version;
        }, function errorCallback(response) {
            return $q.reject(response.data);
        });
    },

稍后,我在我的控制器中使用它:

    $scope.printApiVersion = function () {
    var promise = manager.getApiVersion();
    promise.then(function(version) {
        console.log(version);
    }, function(error) {
        console.log("Couldn't retrieve API version.")
    });
}

这对我很有用,但我不知道它是否被认为是好风格。