angularJS $http get 中的可选参数

Optional Parameters in angularJS $http get

我使用 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 是可选的。目前它总是通过,即使它是空的。

//已编辑

您可以使用如下所示的三元测试:

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

或在创建 return

之前先创建 url
 $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 [];
     });
 }

如果是真的,请将其添加到 url。

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