Roger Roger - 1 month ago 6
HTTP Question

Doing HTTP request on client-side using AngularJS

After successfully finishing this tutorial, I started building my app routes to handle the creation of some dummy models in the database, which works just fine when I request them through Postman app (using the follwing URL: https://lab4-roger13.c9users.io:8080/api/nerds).

The next step, was to create a service in AngularJS to allow the user to request those same informations at the client side. At the end of the tutorial I was left with this:

angular.module('NerdService', []).factory('Nerd', ['$http', function($http) {

return {
// call to get all nerds
get : function() {
return $http.get('/api/nerds');
},

a : 2,

// these will work when more API routes are defined on the Node side of things
// call to POST and create a new nerd
create : function(nerdData) {
return $http.post('/api/nerds', nerdData);
},

// call to DELETE a nerd
delete : function(id) {
return $http.delete('/api/nerds/' + id);
}
}

}]);


And this is the module that links all my services and routes:

angular.module('sampleApp',
['ngRoute', 'appRoutes', 'MainCtrl', 'NerdCtrl', 'NerdService'])
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
$scope.a = Nerd.a;
}]);


Here is a sample of a backend route I'm trying to access:

module.exports = function(app) {

// get all nerds in the database (accessed at GET https://lab4-roger13.c9users.io:8080/api/nerds)
app.get('/api/nerds', function(req, res) {

// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {

// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);

res.json(nerds); // return all nerds in JSON format
});
});


As you can imagine, I can access the
a
property of the service at the html by using the
{{a}}
notation, which displays 2. But when I try the same with the
get
property, nothing shows up.

I'm not sure, is the URL the tutorial provides at the
$http.get
wrong or am I missing a step to do and access the GET response?

(If I missed any relevant code, they are the same as the ones that can be found at the tutorial link)

Answer

Nerd.get() is a function that returns a promise from the $http service. If you want to show it's result in your view, you can bind the results to your view like so:

.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
    Nerd.get().then(function(nerds) {
        $scope.nerds = nerds;
    });
}]);
Comments