我有一个 POST 数据要在 Angular.js 项目中检索。这是我的工厂:
angular.module('mtApp').factory('getKey', function($http) {
return {
getData: function(data) {
var key='';
return $http({
url: '../php/key_gen.php',
method: "POST",
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
console.log(data); //value is right as expected
return data;
})
.error(function (data, status, headers, config) {
console.log('Erro : ' + status + ' ' + headers);
});
}
}
});
我获取数据的方式是:
$scope.key = 'ok';
getKey.getData()
.success(function($scope,data){
$scope.key = data.GeneratedKey;
console.log(data.GeneratedKey); //undefined
console.log(data); //200 o.O
});
console.log($scope.key); //still 'ok' O.o
正如您在我的代码中看到的,我有几个 console.log 调用。当我运行该应用程序时,我唯一看到的是:
mtapp.controller.js:13 ok
mtapp.app.js:52 Object {GeneratedKey: "d1bc7a5e840a6c24d87b90dde9e075de1f0e3b34978ca9f319…69d839b4e2a004e1f8d728939867afe189cfb8848c6a8ee38"}
mtapp.controller.js:9 undefined
mtapp.controller.js:10 200
mtapp.app.js:52 行中的值应与 mtapp.controller.js:10 相同。但是当我尝试在日志中查看时,工厂中的对象只有值 200...
我的目标是将工厂中的 JSON (GenelatedKey) 的值获取到 Controller (在 $scope.key 中)。
我做错了什么? :(
最佳答案
因为您正在处理第二个参数,即状态代码,所以您应该从那里删除 $scope
并使用 data
本身
代码
getKey.getData()
.success(function(data, status, headers, config){ <---here $scope should remove
$scope.key = data.GeneratedKey;
console.log(data.GeneratedKey);
console.log(data);
});
关于javascript - AngularJS : The correct way to factory returning object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29832114/