【问题标题】:How can I change the structure of an AngularJS get request?如何更改 AngularJS 获取请求的结构?
【发布时间】:2016-07-12 01:43:24
【问题描述】:

作为 AngularJS 应用程序的一部分,我有以下状态:

.state('app.stages', {
      url: '/stages',
      views: {
        'menuContent': {
      templateUrl: 'templates/stages.html',
      controller: 'StagesCtrl'
    }
  }
})

.state('app.stage', {
url: '/stages/:stageId',
views: {
  'menuContent': {
    templateUrl: 'templates/stage.html',
    controller: 'StageCtrl'
  }
}

关联的控制器是:

controller('StagesCtrl', function($scope,$http) {
$http.get("http://localhost/apistages")
.then(function(response) {
    $scope.stages = response.data;
});
})

.controller('StageCtrl', function($scope, $http, $stateParams) {

  $http({
    method: 'GET',
    url: 'http://localhost/apistage/',
    params: {stageId: $stateParams.stageId}
 }).then(function successCallback(response) {
    $scope.stage = response.data;
 }, function errorCallback(response) {

  });
});

阶段列表运行良好,但阶段控制器中的查询尝试访问http://localhost/apistage/?stageId=43,导致 500(内部服务器错误)。

我需要使用的 URL 格式是 http://localhost/apistage/43 。如何调整查询以获取该 URL?

【问题讨论】:

    标签: javascript angularjs asynchronous angularjs-http


    【解决方案1】:

    那么不要在 $http GET 请求上使用params 选项。而是在调用服务时在 URL 上使用简单的字符串连接

    $http({
        method: 'GET',
        url: 'http://localhost/apistage/'+$stateParams.stageId //append state parameter in URL itself
    })
    

    对于 REST API,我强烈建议您使用 ngResource($resource) angular 模块。具有很好的处理休息呼叫的能力。

    【讨论】:

    • 我试过这个,但是深夜和被困在 PHP 中一段时间​​导致我使用 .用于连接而不是 +。这么简单的错误。
    【解决方案2】:

    您不应该使用两个控制器。仅使用一个控制器并使用 $routeParams 获取 url 参数。现在您检查参数是否存在,并根据需要区分您的逻辑。您可以使用以下代码: var stageId = $routeParams.stageId; If(stageId) Do something else Do something different

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 2016-07-25
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多