获取工厂变量
Get variable of a factory
我有问题。我正在制作一个应用程序 AngularJS,当在控制器中注入一个工厂时,给我未定义。
问题是当我打电话给工厂时。我无法获得响应的值。
工厂:
app.factory('mapFactory', function($http){
return {
getCoordinates: function() {
return $http.get("http://xxxx/map.php?callback=JSON_CALLBACK").then(function(response){
return response.data;
console.log(response.data); // "37.344/-4.3243"
});
}
}
});
控制器:
app.controller('MapCtrl', function(mapFactory) {
var coordinates;
mapFactory.getCoordinates().then(function(response){
return coordinates = response;
});
console.log(coordinates); // undefined
var elem = coordinates.split('/'); // Cannot read property 'split' of undefined
latitude = elem[0];
longitude = elem[1];
});
$http.get
调用是异步的,所以coordinates = response
会在get request完成后设置,但下面的代码会立即执行。您可以将其余代码移动到 then
函数中以使其工作
app.controller('MapCtrl', function(mapFactory) {
var coordinates;
mapFactory.getCoordinates().then(function(response){
return coordinates = response;
console.log(coordinates);
var elem = coordinates.split('/');
latitude = elem[0];
longitude = elem[1];
});
});
我有问题。我正在制作一个应用程序 AngularJS,当在控制器中注入一个工厂时,给我未定义。 问题是当我打电话给工厂时。我无法获得响应的值。
工厂:
app.factory('mapFactory', function($http){
return {
getCoordinates: function() {
return $http.get("http://xxxx/map.php?callback=JSON_CALLBACK").then(function(response){
return response.data;
console.log(response.data); // "37.344/-4.3243"
});
}
}
});
控制器:
app.controller('MapCtrl', function(mapFactory) {
var coordinates;
mapFactory.getCoordinates().then(function(response){
return coordinates = response;
});
console.log(coordinates); // undefined
var elem = coordinates.split('/'); // Cannot read property 'split' of undefined
latitude = elem[0];
longitude = elem[1];
});
$http.get
调用是异步的,所以coordinates = response
会在get request完成后设置,但下面的代码会立即执行。您可以将其余代码移动到 then
函数中以使其工作
app.controller('MapCtrl', function(mapFactory) {
var coordinates;
mapFactory.getCoordinates().then(function(response){
return coordinates = response;
console.log(coordinates);
var elem = coordinates.split('/');
latitude = elem[0];
longitude = elem[1];
});
});