Search code examples
javascriptangularjsasynchronousangularjs-http

How can I change the structure of an AngularJS get request?


I have the following states as part of an AngularJS app:

.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'
  }
}

The controllers associated are:

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) {

  });
});

The stages list works well, but the query in the stage controller tries to access http://localhost/apistage/?stageId=43 which results in a 500 (Internal Server Error).

The URL format that I need to use is http://localhost/apistage/43 . How can I adjust the query to fetch that URL?


Solution

  • Then don't use params options on $http GET request. Instead just use simple string concatenation on URL while making call to service

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

    For REST API I'd highly recommend you to use ngResource($resource) module of angular. Which has good capability to deal with rest calls.