2016-08-03 2 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にリクエストを送信するために2つのコントローラ、いずれかを使用して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; 
    }); 

れる私問題?そしてコードが間違っている場合は、どこに言及してください。あなたのcontrollerで、

app.factory('myService', function($http) { 
var myService = { 
    getData: getData 
}; 

return myService; 

function getData(link) { 
    return $http.get(link); 
} 
}); 

その後:

答えて

0

はあなたのfactoryからpromise返すことができます

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);  
}); 
関連する問題