AngularJS:从工厂将数据 json 加载到控制器中

AngularJS: Load data json in controller from factory

我无法在控制器中加载数据,return未定义。

我有这个工厂服务:

app.factory('factoryLlamada', function($http,$q) { return{
    cargar: function(archivo) {
        var deferred = $q.defer();
        $http.get(archivo).success(function(data) {
            deferred.resolve(data);
        })
        .error(function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }
}});

还有这个控制器:

app.controller('ctrlProducts', function(factoryLlamada) {
    this.saludo = 'Hola'; //this work's
    factoryLlamada.cargar('prueba.json').then(function(data) {
        this.datos = data;
        console.dir(data);  //return json object (ok)
        console.dir(datos); //return undefined
    })
    .catch(function(error) {
        console.log('Se ha producido un error: '+error);
    });
});

不知道是哪个问题...

回调函数里面的this没有引用controller

改为:

app.controller('ctrlProducts', function(factoryLlamada) {
    var vm = this;
    vm.saludo = 'Hola'; //this work's

    factoryLlamada.cargar('prueba.json').then(function(data) {
        vm.datos = data;
        console.dir(data);  //return json object (ok)
        console.dir(vm.datos);
    })
    .catch(function(error) {
        console.log('Se ha producido un error: '+error);
    });
});

顺便说一下,在工厂中您不必使用 $q 承诺。只要重用 $http.get 返回的 promise,代码就会简洁很多:

app.factory('factoryLlamada', function($http) { return{
    cargar: function(archivo) {
        return $http.get(archivo);
    }
}});

并像这样检索数据:

factoryLlamada.cargar('prueba.json').then(function(response) {
    // data is in response.data
});