AngularJS:Factory $ http赋值返回null

时间:2015-07-22 16:16:52

标签: javascript angularjs angularjs-factory

我试图从$ http.get()中分配一个变量尽管conf var为null,尽管请求通过并返回json。

app.factory('Config', ['$http',
    function($http) {
        return {

            conf: null,

            init: function () {

                if (this.conf === null) {
                    $http.get('/config')
                        .success(function (data) {
                            this.conf = data;
                        });
                }
            }
        }
    }
]);

1 个答案:

答案 0 :(得分:2)

this内的{p> success callback function是不同的

app.factory('Config', ['$http',
    function($http) {
        return {

            conf: null,

            init: function () {
                var self = this;
                if (this.conf === null) {
                    $http.get('/config')
                        .success(function (data) {
                            self.conf = data;
                        });
                }
            }
        }
    }
]);