1

So I'm getting into Angular and I've made a succesfull api call which returns objects with a name and a url. To get details of an object I need to do another api call which has the id of the object in it. I'm not sure how to do this.

This is my service to make the api call for the details of the object. the ':id' is where the id of the object has to go in the api link

app.factory('pokemonDetails', ['$http', function($http) {
return $http.get('http://pokeapi.co/api/v2/pokemon/:id')
    .success(function(data) {
        return data;
    })
    .error(function(err) {
        return err;
    });
}]);

I'm not sure if I'm explaining this clearly.

When I go to my url '/pokemon/1', the api has to call 'http://pokeapi.co/api/v2/pokemon/1'.

If I go to my url '/pokemon/2', the api has to call 'http://pokeapi.co/api/v2/pokemon/2' and so on..

(I'm not sure if I need to share other parts of my code, if I do tell me and I'll add them.)

1

2 Answers 2

1

This is a good use case for angular's $resource service, if you'd like to use it.

var Pokemon = $resource('http://pokeapi.co/api/v2/pokemon/:id', {id:'@id'});
var thisPokemon = Pokemon.get({id:1}, function() {
  /* whatever you want to do after you get the details back */
});

$resource is kind of a shorthand that allows you to make standard (and custom) CRUD operation calls on your API resources.

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

Comments

0

Define a function that has a parameter.

app.factory('pokemonDetails', ['$http', function($http) {
     function httpPromise(id) {
         return $http.get('http://pokeapi.co/api/v2/pokemon/'+id);
     }
     //return function
     return httpPromise
}]);

Then use it in your client code.

$scope.details=[];
for (var id=0; id < someNumber; id++) {
    pokemanDetails(id).then( function onFulfilled(response) {
        $scope.details[id] = response.data;
    }).catch ( function onRejected (response) {
        console.log ( response.status );
    });
};

The key is passing parameters to a function.


Deprecation Notice

The $http legacy promise methods .success and .error have been deprecated. Use the standard .then method instead.1

1 Comment

Does the second part go in the controller? or do I have to add some other code somewhere? (Sorry, I'm a real noob when it comes to Angular) :/

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.