javascript – Angular – 在服务URL中使用范围变量
作者:互联网
目前,我想从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);
});
我已经read将$scope传递给服务是不可能的(并且不应该这样做),所以如何将scope变量用作服务中的参数,是否有更简洁的方法来设置除了添加字符串myUrl搜索之外的参数?
完整代码:
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
});
}
});
解决方法:
只需将搜索作为参数传递给服务函数:
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;
};
});
标签:javascript,angularjs,angular-services 来源: https://codeday.me/bug/20190702/1352481.html