Loading a view routed by a URL parameter (e.g., /users/:id) in MEAN stack

Posted by Matt Rowles on Stack Overflow See other posts from Stack Overflow or by Matt Rowles
Published on 2014-06-07T02:16:05Z Indexed on 2014/06/07 3:26 UTC
Read the original article Hit count: 158

I am having difficulties with trying to load a user by their id, for some reason my http.get call isn't hitting my controller.

I get the following error in the browser console:

TypeError: undefined is not a function
    at new <anonymous> (http://localhost:9000/scripts/controllers/users.js:10:8)

Update I've fixed my code up as per comments below, but now my code just enters an infinite loop in the angular users controllers (see code below).

I am using the Angular Express Generator for reference

Backend - nodejs, express, mongo

routes.js:

// not sure if this is required, but have used it before?
app.param('username', users.show);

app.route('/api/users/:username')
    .get(users.show);

controller.js:

// This never gets hit
exports.show = function (req, res, next, username) {
    User.findOne({
        username: username
    })
    .exec(function (err, user) {
        req.user = user;
        res.json(req.user || null);
    });
};

Frontend - angular

app.js:

$routeProvider
    .when('/users/:username', {
        templateUrl: function( params ){ return 'users/view/' + params.username; },
        controller: 'UsersCtrl'
    })

services/user.js:

angular.module('app')
    .factory('User', function ($resource) {

        return $resource('/api/users/:username', {
            username: '@username'
        }, {
            update: {
                method: 'PUT',
                params: {}
            },
            get: {
                method: 'GET',
                params: {
                    username:'username'
                }
            }
        });
});

controllers/users.js:

angular.module('app')
.controller('UsersCtrl', ['$scope', '$http', '$routeParams', '$route', 'User', function ($scope, $http, $routeParams, $route, User) {

        // this returns the error above
        $http.get( '/api/users/' + $routeParams.username )
            .success(function( user ) {
                $scope.user = user;
            })
            .error(function( err) {
                console.log( err );
            });
}]);

If it helps, I'm using this setup

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about node.js