Angular - 在服务URL中使用范围变量

时间:2016-10-13 00:25:47

标签: javascript angularjs angular-services

目前,我希望从API获取数据,使用AngularJS服务发送一些搜索参数。在我的ng模型中,我有一个名为search的变量,我想将该变量用作API URL的参数。

我的第一个(不成功)方法是直接在服务中使用$ scope.search变量:

$http.get('http://www.omdbapi.com/?s='+ $scope.search +'&type=series&r=json').then(function(data){
     deferred.resolve(data);
});

我{$ 3}}将$ scope传递给服务是不可能的(也不应该这样做),那么如何将scope变量用作服务中的参数还有,除了添加字符串myUrl + search之外,还有更简洁的方法来设置参数吗?

完整代码:

 myApp.service('showsService', function($http, $q){
    var deferred = $q.defer(); //promise to say 'im going to do this later'
    $http.get('http://www.omdbapi.com/?s=sherlock&type=series&r=json').then(function(data){
        deferred.resolve(data);
    });
    this.getShows = function(){
        return deferred.promise;
    }
    });

    myApp.controller("showsController", function($scope, showsService){
    $scope.$watch('search', function() {
      fetch();
    });

    function fetch(){
        var promise = showsService.getShows();
        promise.then(function(data){
        $scope.showsResult = data.data.Search; //using the name than comes back from the API
    });
    }
    });

2 个答案:

答案 0 :(得分:2)

只需将search作为参数传递给服务函数:

myApp.service('showsService', function($http){
    this.getShows = function(search){
        var url = 'http://www.omdbapi.com/s='+search+'&type=series&r=json';
        var promise = $http.get(url);
        return promise;
    };
});

然后在控制器中:

myApp.controller("showsController", function($scope, showsService){
   $scope.$watch('search', function(value) {
      fetch(value);
   });

   function fetch(search){
       var promise = showsService.getShows(search);
       promise.then(function(response){
           $scope.showsResult = response.data.Search;
       });
    };
});

由于$q.defer服务已经返回承诺,因此无需使用$http制作承诺。

更新

$http服务能够序列化参数:

myApp.service('showsService', function($http){
    this.getShows = function(search){
        //var url = 'http://www.omdbapi.com/s='+search+'&type=series&r=json';
        var url = 'http://www.omdbapi.com/'
        var config = { 
            params: { 
                s: search,
                type: 'series',
                r: 'json'
            }
        };
        var promise = $http.get(url, config);
        return promise;
    };
});

答案 1 :(得分:0)

您可以直接将搜索数据传递给服务

var getShows = showsService.getShows($scope.search);
getShows.then(function(resposne){
    console.log(resposne.data);
})

服务代码

myApp.service('showsService',['$http',function commonSrv($http) {
this.getShows=function(search)
      {
        var promise = $http({
          method: 'post',
          url: 'http://www.omdbapi.com/',
          data:{"s":search, 'type':'series'},
          contentType:'application/json; charset=UTF-8',
        });
        return promise;
      };
}]);
相关问题