0

我有一项服务可以进行一些调用以检索要在我的应用程序中使用的数据。加载数据后,我需要调用另一个服务对我的数据进行一些操作。问题是第二个服务将无法访问第一个服务的数据。

我做了一个 plunker:plunkr

首次服务

app.factory('Report', ['$http', function($http,$q){
var Authors = {

    reports : [],
    requests :[{'url':'data.json','response':'first'},
               {'url':'data2.json','response':'second'}, 
               {'url':'data3.json','response':'third'}]

};

Authors.getReport = function(target, source, response, callback) {
    return $http({  url:source, 
                    method:"GET", 
                    //params:{url : target}
                }).success(function(result) {
                    angular.extend(Authors.reports, result)
                    callback(result)
      }
      ).error(function(error){
                })   
}

    Authors.startQueue = function (target,callback) {
        var promises = [];
        this.requests.forEach(function (obj, i) {
            console.log(obj.url)
            promises.push(Authors.getReport(target, obj.url, obj.response,  function(response,reports){
                callback(obj.response,Authors.reports)
            }));
        });
    } 


return Authors;

}])

二次服务

app.service('keyService', function(){
this.analyze = function(value) {
    console.log(value)
    return value.length
}
});

控制器

在控制器中,我尝试类似:

    $scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports,keyService) {
        $scope.progressBar +=33;
        $scope.progress = response;
        $scope.report = reports;

    });

$scope.test = function(value){
    keyService.analyze($scope.report.about);
}
4

1 回答 1

0

我想这就是你想要的?本质上,您希望在第一个服务成功后调用第二个服务。还有其他方法可以做到这一点,但根据您的示例,这是最简单的。

http://plnkr.co/edit/J2fGXR?p=preview

$scope.result = Report.startQueue('http://www.prestitiinpdap.it', function (response,reports) {
    $scope.progressBar +=33;
    $scope.progress = response;
    $scope.report = reports;
    $scope.test($scope.report.about); //added this line
});

  $scope.test = function(value){
    $scope.example = keyService.analyze(value); //changed this line to assign property "example"
  }


  <body ng-controller="MainCtrl"> 
    <p>Hello {{name}}!</p>
    <p>Progress notification : {{progress}}!</p>
    <div ng-show="show">
    <progress percent="progressBar" class="progress-striped active"></progress>
    </div>
    <pre>{{report}}</pre>
    <pre>{{report.about}}</pre>

    {{example}} <!-- changed this binding -->
  </body>
于 2013-09-20T17:25:52.453 回答