1

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)

Roger
  • 1,053
  • 1
  • 8
  • 14

2 Answers2

2

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;
    });
}]);
Anid Monsur
  • 4,538
  • 1
  • 17
  • 24
  • What is the difference between using $scope or attaching the variables to the controller? On the documentation, most of the time I see it attached to the controller, and when I try to use $scope it wont work. Also, when I try to attach my variables to the controller instead of using $scope, it doesn't work aswell... – Roger Nov 25 '15 at 05:24
  • It depends whether or not you're using `controllerAs` syntax. I assumed you were not, since your code used `$scope`. [Here's a good article explaining the differences](http://toddmotto.com/digging-into-angulars-controller-as-syntax/). – Anid Monsur Nov 25 '15 at 05:29
  • Thanks alot, I got it to work properly now with this instead of $scope! I've already implemented the create and delete functions and they work just fine. One issue I noticed, is that while those last two seem to instantly update the Database (checking with Postman), the get method seems to keep getting an old version of it, you have any tips on what it might be? – Roger Nov 26 '15 at 03:01
2

loved this post I had some problem using factory and found solution here nerds controller

angular.module('NerdCtrl', []).controller('NerdController', function($scope, Nerd) {


    $scope.tagline = 'bla bla';

    $scope.nerds = {};
    Nerd.getNerd()
        .then(function (components) {
            $scope.nerds = components;
        }, function (error) {
            console.error(error);
        });

});

As service

angular.module('NerdService', []).factory('Nerd', function ($q, $http) {
    return {
      getNerd: function () {
        var deferred = $q.defer(),
          httpPromise = $http.get('/api/nerds');

        httpPromise.success(function (components) {
          deferred.resolve(components);
        })
          .error(function (error) {
            console.error('Error: ' + error);
          });

        return deferred.promise;
      }
   };
});

In NerdHTLM using controller to loop records

<table ng-controller="NerdController" >
    <tbody>
        <tr ng-repeat="nerd in nerds">
            <td>{{nerd.name}}</td>
            <td>{{nerd.type}}</td>
        </tr>
    </tbody>
</table>
Smittey
  • 2,475
  • 10
  • 28
  • 35
Nicolas
  • 69
  • 5
  • I found great explanation about Factory retrieving Data from MongoDB here [link](https://programmaticponderings.com/2014/03/24/retrieving-and-displaying-data-with-angularjs-and-the-mean-stack-part-ii-2/). enjoy ! (thx Roger and Anid) – Nicolas Oct 19 '16 at 09:49