Angular -在服务url中使用作用域变量

Angular - Use scope Variable in Service url

本文关键字:作用域 变量 url 服务 Angular      更新时间:2023-09-26

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

我的第一个(不成功的)方法是使用$作用域。直接在服务内部搜索变量:

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

我读到传递$作用域到服务是不可能的(无论如何也不应该这样做),所以我怎么能在服务中使用作用域变量作为参数,还有,除了添加字符串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
    });
    }
    });

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;
       });
    };
});

由于$http服务已经返回了一个承诺,所以不需要用$q.defer制作承诺。


更新

$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;
    };
});

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

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;
      };
}]);