app.factory('myService', function ($http) {
var myService;
var getData = function(link) { //function to get some data from a get request to 'link'
$http.get(link)
.success(function(response) {
myService = response.data;
});
return myService;
};
return myService;
});
我正在使用两个控制器,一个用于向myService发送请求以从搜索中获取搜索结果并将结果存储在myService中,而另一个控制器是另一个页面(但是相同的应用程序),我必须在其中显示结果。
以下控制器是获取搜索结果并将其存储在myService中:
app.controller('headerController', ['$scope', function($scope,$http,myService) {
$scope.search_it=function(name,link) { //this is called from html, providing the name and link arguments, with link containing the link to get data from
$scope.respons = myService.getData(link);
};
}]);
以下控制器是从myService获取数据以在另一页上查看:
app.controller("resultController", function ($scope,myService) {
$scope.resJSON = myService;
});
我的问题在哪里?如果代码不正确,请提及哪里。
答案 0 :(得分:0)
您可以从promise
factory
app.factory('myService', function($http) {
var myService = {
getData: getData
};
return myService;
function getData(link) {
return $http.get(link);
}
});
然后,在controller
:
app.controller('headerController', function($scope, $http, myService) {
$scope.search_it = function(name, link) { //this is called from html, providing the name and link arguments, with link containing the link to get data from
function getSuccess(response) {
$scope.respons = response.data;
}
function getError(response) {
console.log(response);
}
myService.getData(link)
.then(getSuccess)
.catch(getError);
});