2016-08-03 58 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);  
}); 
相關問題