本文介绍了Angularjs;使用服务返回的$ HTTP引用,而不是实际的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的Angularjs服务指令的不出厂,我需要填充JSON文件下载到本地变量;
/ *包含项目在镇* /
leMaireServicess.service('cityService',函数($ HTTP){ // JSON地区和城市装载机
this.cities = []; // initCities
this.initCities =功能(){
this.cities = $ http.get(数据/政府/ cities.js')。成功(功能(数据){
返回的数据;
});
返回this.cities;
}; //获取城市信息
this.getCity =功能(){
返回this.cities;
};
});
在我的控制器我有
//保存的游戏控制器
leMaireControllers.controller('GameCoreCtrl',函数($范围,cityService){ / *控制镇项目幻灯片* /
cityService.initCities();
$ scope.city = cityService.getCity(); 的console.log($ scope.city);
});
但是,而不是返回的实际数据,它将返回;
对象{则:功能,美中不足的是:函数,最后:功能,成功:函数,错误:函数}
解决方案
您可以用手表来完成这项工作(的)
VAR应用= angular.module('plunker',[]);app.controller('MainCtrl',函数($范围,cityService){
//$scope.cities = [];
$ scope.service = cityService;
cityService.initCities();
$范围。$腕表('service.getCity(),功能(的newval){
$ scope.cities =的newval;
的console.log(的newval)
});
});app.service('cityService',函数($ HTTP){
VAR认为这=;
this.cities = []; this.initCities =功能(){
$ http.get('data.js')。成功(功能(数据){
that.cities = data.cities;
});
}; this.getCity =功能(){
返回this.cities;
};
});
I'm using the services directive in Angularjs not factory and I need to populate a json file to local variable;
/* Contains projects on the town */
leMaireServicess.service('cityService', function($http) {
// JSON regions and cities loader
this.cities = [];
// initCities
this.initCities = function() {
this.cities = $http.get('data/census/cities.js').success(function(data) {
return data;
});
return this.cities;
};
// Get city info
this.getCity = function() {
return this.cities;
};
});
And in my controller I have
// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {
/* Control the town project slides */
cityService.initCities();
$scope.city = cityService.getCity();
console.log($scope.city);
});
But instead of returning the actual data, it returns;
Object {then: function, catch: function, finally: function, success: function, error: function}
解决方案
You can use a watch to make this work (see plunker)
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,cityService) {
//$scope.cities = [];
$scope.service = cityService;
cityService.initCities();
$scope.$watch('service.getCity()', function(newVal) {
$scope.cities = newVal;
console.log(newVal)
});
});
app.service('cityService', function($http) {
var that = this;
this.cities = [];
this.initCities = function() {
$http.get('data.js').success(function(data) {
that.cities = data.cities;
});
};
this.getCity = function() {
return this.cities;
};
});
这篇关于Angularjs;使用服务返回的$ HTTP引用,而不是实际的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!