0

我是角度 JS 的新手。我有一个控制器(.js 文件),我在其中编写了一个函数来对后端进行 http get 调用。如下所示:

             $http({
                 url: "services/rest/1.0/project/employeeDetails",
                 method: 'GET',
                 headers: config,
                 transformResponse: function (data) {
                     var x2js = new X2JS();
                     var json = x2js.xml_str2json(data);
                     return json;
                 }
             }).success(function (response) {
                 alert("success for account details with response:"+response);
                if (response && response.siteDetailsList.errorCode == 0)
                     $scope.accountdetails = response;
             });

现在的问题是我需要向我在上面代码片段中提到的 url 添加两个查询参数,以便最终 URL 看起来像这样:

services/rest/1.0/project/employeeDetails ? param1=world & param2=hello

这个 param1 和 param2 值是从我的 HTML 文件的输入文本框中获得的。知道我们如何将动态查询参数附加到此 URL 吗?

4

4 回答 4

1

您可以使用$httpParamSerializer来自 AngularJS 的服务。

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

目的:

var obj = {
  param1:"world",
  param2:"hello"
}

使用 httpParamSerializer:

$httpParamSerializer(obj)

回报:

param1=test&param2=world
于 2017-02-16T09:19:19.293 回答
1

您可以使用params配置属性:

   $http({
         url: "services/rest/1.0/project/employeeDetails",
         method: 'GET',
         headers: config,
         params: {
             param1: someValue,
             param2: anotherValue
         },
         transformResponse: function (data) {
             var x2js = new X2JS();
             var json = x2js.xml_str2json(data);
             return json;
         }
     }).success(function (response) {
         alert("success for account details with response:"+response);
        if (response && response.siteDetailsList.errorCode == 0)
             $scope.accountdetails = response;
     });
于 2017-02-16T08:41:35.180 回答
0

我解决了这个问题。它非常简单。我们也可以这样修改 $url:

$http({
         url: "services/rest/1.0/project/employeeDetails?param1="+value+"&param2="+value",
         method: 'GET',
         headers: config
         }

使用单独的“param”属性有点棘手,因为默认情况下参数按字母顺序排序,所以如果我们希望参数以我们想要的顺序出现,我们需要编写代码来防止排序。

最后,感谢您的及时回复。:)

于 2017-02-17T06:42:19.197 回答
0
var obj = 
{
  param1:"world",
  param2:"hello"
}

$http.post("services/rest/1.0/project/employeeDetails", obj)
.then(function (response)
{
        return response`enter code here`;
},`function (error)

{返回错误;});`

于 2017-02-16T09:57:33.273 回答