angularJS $ http get中的可选参数

时间:2015-12-18 15:20:48

标签: javascript angularjs slim

我使用Slim Framework构建了一个API。 我在Slim中的一条路线接受可选参数。 有什么方法可以使用angularjs $http.get来做到这一点。如何在我的请求中设置可选参数。

以下是我的代码;

$scope.getRestaurant = function () {
    return $http({
        method: 'get',
        url: "http://api.example.co.uk/web/restaurant/details/" + $scope.id + "/" + $scope.u,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        return response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        return [];
    });
}

如您所见,我有$scope.id$scope.u。我希望$scope.u是可选的。目前,即使它为空,它也总是被传递。

2 个答案:

答案 0 :(得分:1)

如果它真实的话,只需将其添加到网址。

var baseUrl = 'http://api.example.co.uk/web/restaurant/details/' + $scope.id;
if($scope.u) baseUrl += '/' + $scope.u;

答案 1 :(得分:0)

//编辑

你可以使用像下面这样的三元测试:

 $scope.getRestaurant = function () {
     return $http({
         method: 'get',
         url: "http://api.example.co.uk/web/restaurant/details/" + $scope.id + 
             ( $scope.u != null ) ? "/"+$scope.u : ""   ,
         headers: {'Content-Type': 'application/x-www-form-urlencoded'}
     }).then(function successCallback(response) {
         // this callback will be called asynchronously
         // when the response is available
         return response.data;
     }, function errorCallback(response) {
         // called asynchronously if an error occurs
         // or server returns response with an error status.
         return [];
     });
 }

或在您返回之前创建您的网址

 $scope.getRestaurant = function () {

     var url  = "http://api.example.co.uk/web/restaurant/details/" + $scope.id +
             ( $scope.u != null ) ? "/"  +$scope.u : "" ;

     return $http({
         method: 'get',
         url: url,
         headers: {'Content-Type': 'application/x-www-form-urlencoded'}
     }).then(function successCallback(response) {
         // this callback will be called asynchronously
         // when the response is available
         return response.data;
     }, function errorCallback(response) {
         // called asynchronously if an error occurs
         // or server returns response with an error status.
         return [];
     });
 }