我正在尝试从角度服务进行$ http调用,但它似乎没有反映在html中
var heroSliderApp = angular.module('heroSliderApp', []);
heroSliderApp.service('heroService', function ($http) {
this.loadSlider = function () {
$http.get("some url that returns data")
.then(function (response) {
return JSON.stringify(response.data);
//return "Hello World!"; //this doesn't work
});
};
});
heroSliderApp.controller('heroSliderController', function ($scope, $http, heroService) {
$scope.sliderValue = heroService.loadSlider(); // this doesn't work
$scope.someValue= "Testing"; //this works
});
此处调用.then函数,response.data包含值,但该值未反映在html中
答案 0 :(得分:1)
试试这个
this.loadSlider = function () {
return $http.get("some url that returns data")
.then(function (response) {
return JSON.stringify(response.data);
//return "Hello World!"; //even this doesn't work!
});
};
heroService.loadSlider ().then(function(d) {
$scope.sliderValue = d;
});
答案 1 :(得分:1)
好的,所以我根据@JB Nizet的评论修改了它似乎工作
var heroSliderApp = angular.module('heroSliderApp', []);
heroSliderApp.service('heroService', function ($http) {
this.loadSlider = function () {
return $http.get("some url here");
};
});
heroSliderApp.controller('heroSliderController', function ($scope, $http, heroService) {
$scope.sliderValue = "";
heroService.loadSlider().then(function (response) {
$scope.sliderValue = response;
});
});
答案 2 :(得分:-1)
更改您的服务
heroSliderApp.service('heroService', function ($http) {
this.loadSlider = function () {
$http.get("some url that returns data")
.success(function (response) {
return JSON.stringify(response.data);
//return "Hello World!"; //even this doesn't work!
}).error(function {
//Erro handler
});
};
});
和控制器一样
heroService.loadSlider().then(function(response) {
$scope.sliderValue = response;
})
现在服务将返回一个承诺,控制器将收到它。当控制器数据从服务接收到响应时,数据将被绑定在控制器变量中。