Search code examples
javascriptajaxnode.jsangularjsasynccallback

AJAX data transfer between angularjs front-end and nodejs back-end


FYI: There is main question on the bottom if you ever feel like my post is too long ;)

Im trying to build my first angularjs app and now Im stuck with collecting data via ajax from nodejs (express) server.

In front-end Im loading templates with angularjs routers and ng-view. In every route i have template and specific controller (this should be pretty basic thing right?).

OK here comes the wall... I was thinking to put $http.get() to load right stuff for the template from the nodejs server in the controller. With GET I could send variables like this.

$http.get('http://.../API', { params: { twitterData : true,  needed : "data2" } } )
    .success( function(result) {
        // pass result to template.
    });

And then on the server side get params like this.

router.get('/', function(req, res) {
    this.params = req.query;

    // here run every function and collect it to one object
    // then return it for front-end ajax call.

   res.send(JSON.stringify(collectedDataObj));
}

collectedDataObj could look something like this:

{ twitterData : 
    { thisIs:twitterObject }, 
    blog : {title: "...", content: "..." } 
}

Collecting data would be by nested callbacks like introduced here http://book.mixu.net/node/ch7.html

So is this "collecting all data in back-end" best way to get data or should I send many ajax calls to collect data for one angular view?

Meaning one $http.get() for getting titter object and one for blog content etc.

And of course if you know some pass me links for good tutos/examples.


Solution

  • IMO, whenever possible it's best to get everything you can in one request. Trips back and forth to the server get pretty expensive.