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;
});
Где моя проблема? И если код неправильный, укажите где.
Вы можете вернуть 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);
});