Dominic Dominic - 6 months ago 16
Javascript Question

Trouble making a simple API call with Angular

Why is it that when I try to retrieve data with this simple API call I get an error that says http://127.0.0.1:8080/%7B%7Buser.avatar%7D%7D <- ? But if I move my promise into my controller it works. I thought that you can make your promises in your service and it'll work fine?

This is my controller.js file

angular.module('userProfiles').controller('MainController', function($scope, mainService) {

$scope.getUsers = function() {
mainService.getUsers();
}
$scope.getUsers();

});


This is my services.js file

angular.module('userProfiles').service('mainService', function($http) {
var baseUrl = 'http://reqres.in/api/users?page=1';

this.getUsers = function() {
return $http({
method: 'GET',
url: baseUrl
}).then(function(response) {
this.users = response.data.data;
});
}
});

Answer

You aren't assigning the response.data.data to anything usable outside that callback. Try it like this instead, returning a promise that resolves with the users data...

this.getUsers = function() {
    return $http.get('http://reqres.in/api/users', {
        params: {page: 1}
    }).then(function(res) {
        return res.data.data;
    });
};

and in your controller

$scope.getUsers = function() {
    mainService.getUsers().then(function(users) {
        $scope.users = users;
    });
};