1

I just started with learning Angular and now i'm busy with an web application that shows some records i fetched from a JSON. The JSON looks like:

"results": [
    {
    "easy": false,
    "id": 1,
    "title": "title",
    }
]

i am parsing that on this way (seems correct to me)

var app = angular.module("DB", []);

app.controller("Controller", function($scope, $http) {
    $http.defaults.headers.common["Accept"] = "application/json";
    $http.get('api_url').

    success(function(data, status, headers, config) {
      $scope.thing = data.results;
    });
});

So now that i am in this JSON file i need to get the ID (in this case its 1) and with that ID i need to do a new request api.com/game/{id} to get more detailed information about the result from the first file.

What is the best way to do that?

1
  • You should user a factory or a service to make your API calls then inject factory or service into your controller. Commented Sep 5, 2014 at 18:56

3 Answers 3

1
$http.get('api.com/game/' + $scope.thing.id, function(...){ });

Point to note, you do not have to manually parse JSON with angular. It will do that for you. So data.results already has the object representing your response.

Sign up to request clarification or add additional context in comments.

Comments

0

i think it is good idea if you do like this:

var app = angular.module("DB", []);

        app.controller("Controller", function($scope, $http) {
            $http.defaults.headers.common["Accept"] = "application/json";
            $http.get('api_url').

            success(function(data, status, headers, config) {
              $scope.thing = data.results;
              $scope.id=data.results[0].id;
              gameInfo();
            });
        });

    var gameInfo=function(){
    $http.get('api.com/game/'+$scope.id).

            success(function(data, status, headers, config) {
              $scope.newThing = data;
            });
    }

Comments

0

Also take a look at ngResource which is a module that gives you more fine-grained control over HTTP requests. It does parameter replacement among other things (custom interceptors, etc.)

https://docs.angularjs.org/api/ngResource/service/$resource

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.