2016-08-03 72 views
0
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

您可以返回从factory一个promise

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);  
}); 
相关问题