sam*_*207 1 angularjs angular-services
我正在尝试编写一个Angular服务,似乎有些东西丢失了.我的问题是它没有向Angular控制器返回任何值
getPrepTimes() 方法不返回http数据
但是当我检查网络时(通过Chrome开发工具),它将正确调用外部api并返回一个json对象作为响应
#my service
'use strict';
angular.module('recipeapp')
.service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes();
function getPrepTimes(){
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function (data, status, header, config){
return data;
});
};
}
]);
#controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime;
}]);
Run Code Online (Sandbox Code Playgroud)
当我getPrepTimes()通过返回字符串检查方法时,它可以工作.这里可能缺少什么?
tym*_*eJV 12
以上几点都有问题.你分配this.prepTime给getPrepTimes().在()那里将调用getPrepTimes立即,而不是当你真正把它!您还需要利用回调来获取数据并使用它:
angular.module('recipeapp').service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes;
function getPrepTimes(callback) {
$http({
url: '/prep_times/index.json',
method: 'GET'
}).success(function (data, status, header, config){
callback(data);
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
现在使用它如下:
prepTimeService.prepTime(function(data) {
$scope.prep_time = data;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9070 次 |
| 最近记录: |