3

I come from a completely non web-development background, but having seen the traction that mean.js is picking up, i really wanted to give it a shot.

I've followed tutorials online so I've basically started, run and modified the example app but am now trying to do something thats off of the tutorials. As a result I have a basic understanding of express and angular

I've been trying to integrate the activator npm package (https://www.npmjs.org/package/activator) into the app, and while I've managed to fit in the angular bits, I'm having trouble plugging in the express bits. Which brings me to a very fundamental doubt, the answers to which I haven't really been able to find. I know that in Mean, the angular code connects to the express code using REST API's created in express. And that I believe happens using angular services. But I don't understand how. For instance, the users module has the following service defined:

angular.module('users').factory('Users', ['$resource',
    function($resource) {
        return $resource('users', {}, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

Can anyone explain how this works ?

Also if I have some code on the express side say:

var sayHello = function(name){
 return "Hello"+name;
}

How can I call this through angular? I know we use $resource for that from the ngResource module, but I dont really understand how.

Any help would be much appreciated.

Karan Kapoor
  • 227
  • 2
  • 12

1 Answers1

6

Connecting these things together can be a bit confusing. I think the thing to understand is that when using Express on the server side, you need to model your API around a route, and handle communication with the req and res objects you'll be handed.

So first on the client side, taking a simple example, I generally use the $resource as a way of wrapping the HTTP/ajax details which I don't want to worry about. So I'll write my service as such:

"use strict";

angular.module("myModule").factory("UserService", ["$resource",
    function($resource) {
        var resource;

        resource = $resource("/api/users", null, {
            listUsers: {
                method: "GET",
                isArray: true
            }
        });

        return resource;
    }
]);

(Notice that I'm passing the isArray parameter to this resource since I expect an array of users to return -- which is not always the case with all APIs).

Then to take advantage of that resource, perhaps in my controller I'll have code like this:

"use strict";

angular.module("myModule").controller("UserCtrl", ["$scope", "UserService",
    function($scope, userService) {

        $scope.loadUsers = function() {
            userService.listUsers(function(resource, headers) {
                // this function is called on success, with the result
                // stored within the `resource` variable

                // ...

            }, function(response) {
                // this function is called on error

                // ...

            });
        };
    }
]);

Now assuming everything goes right on the server side, we'll receive our list of users to play around with passed in to the first function as the resource.

On the server side, we'll need to configure our routes (wherever those are configured) to include our users controller, which will serve as our users API. So perhaps within this app we have a routes directory which contains all our Express routes (see the app.route documentation for more information on Express routes). We also have a controllers directory which contains all our Express controllers that handle the logic for our routes. Keeping with the "users" example, we'll have a route defined that matches the /api/users $resource route we defined above in our Angular code:

"use strict";

var controller = require("../controllers/user");

module.exports = function(app) {
    app.route("/api/users").get(controller.listUsers);
};

This code takes in the Express app as input, and defines a single route for /api/users as a GET HTTP request (notice the .get function called). The logic for this route is defined in the user controller, which would be something like this:

"use strict";

exports.listUsers = function(req, res) {
    var users;

    // ...somehow populate the users to return...

    res.send(users);
};

We've left the details on how to populate that array of users, but hopefully this gives you the idea. This controller is passed the req (request) and res (response) HTTP objects as input, so it can query the request object for details on what the user passed in, and must send some response back to the user to complete the request/response loop. In this example I'm using the res.send function to simply send back our JavaScript array (which will be passed as JSON).

Does that make sense?

dylants
  • 22,316
  • 3
  • 26
  • 22
  • 1
    Thats by far one of the best example explanations I've read anywhere on the internet so far! I like it enough not to purchase the MEAN web development book anymore! However, since you have come so far, could you also add how I could pass a parameter through for the get request in this example, say a user ID. – Karan Kapoor Nov 23 '14 at 18:06
  • Thanks, that's very nice of you to say! :) Happy to help! To pass a parameter, typically I would define the parameter within the route (`/api/users/:userId`) and then within the controller access it via `req.params.userId`. For more information [see the documentation on req.params](http://expressjs.com/4x/api.html#req.params). There's also [documentation on req.body](http://expressjs.com/4x/api.html#req.body) to handle POST requests. You also might benefit from looking at this app I wrote to help some folks a couple months ago: https://github.com/dylants/colors – dylants Nov 24 '14 at 02:25