【问题标题】:Using params in $http GET request in Angular在 Angular 的 $http GET 请求中使用参数
【发布时间】:2014-10-09 08:44:36
【问题描述】:

我将 $http 请求放入服务中。但是,它应该根据用户对表单的输入来检索数据。 url 属性定义了 baseUrl,params 属性定义了 flexibel URL。

angular.module('mean.system').service('flightReq',function($http,$location){
    var baseUrl='/system/views/airfareData.json';
    var method='GET';
    var Request={};
    this.flightReq=function(){
        $http({
            method:method,
            url:baseUrl,
            headers:{'Content-Type': 'application/x-www-form-urlencoded'},
            params: {'dep':'a', 'arr':'b','number':'c', 'date1':'d'},
            cache:true
        })
        .success(function(data,status){
            console.log(data);
            console.log(status);
            $location.path('/resultpresentation/example');
            Request=data;
        })
        .error(function(data){
            console.log(data||"Request failed");
            $location.path('/');
        });

        };
    this.getRequest=function(){
        return Request
    };
});

如您所见,params 被定义为固定为 'a'、'b'、'c'、'd'。但我希望它是灵活的,具体取决于用户的输入。我该怎么做?

如果 $http 请求是控制器而不是服务,我可以简单地执行 $scope.dep 等。但是,在这种情况下我不知道该怎么做。有什么建议么?干杯

【问题讨论】:

  • 只需将包含参数的对象传递给您的 $http 调用。
  • 你的意思是,我应该传入一个从控制器获得的对象(我存储用户输入的地方)?我该怎么做?
  • 只需将$scope.yourModelWithUserInput 作为参数传递给服务,然后将该参数用作参数
  • 抱歉,我好像有点糊涂了。我将所有输入字段命名为 ng-model="formData.dep" ng-model="formData.arr" 等并定义了 $scope.formData={}。因此,每个输入都会立即存储到 formData 中。如果我现在将 formData 注入到我的服务中,我将收到一个错误:Unknown provider

标签: angularjs http service get params


【解决方案1】:

将您的服务注入您的控制器:

.controller('someNameCtrl', ['$scope', 'flightReq', function($scope, flightReq) {

}

然后从控制器中,您将范围作为参数传递给服务

.controller('someNameCtrl', ['$scope', 'flightReq', function($scope, flightReq) {
 ...
    flightReq.flightReq($scope.formData.dep,$scope.formData.arr,$scope.formaData.number,$scope.formData.date1);
 ... 
}

您的服务将接受这些参数并将它们用作参数:

angular.module('mean.system').service('flightReq',function($http,$location){
   var baseUrl='/system/views/airfareData.json';
   var method='GET';
   var Request={};
   this.flightReq=function(dep,arr,number,date1){
    $http({
        method:method,
        url:baseUrl,
        headers:{'Content-Type': 'application/x-www-form-urlencoded'},
        params: {'dep': dep, 'arr': arr,'number': number, 'date1': date1},
        cache:true
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2015-02-03
    • 2020-09-11
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多