Sadeghbayan
Sadeghbayan

Reputation: 1163

show current user information from node to angular

I want to show current user information from nodejs to angular(view).

The problem is that i don't know how to pass and how to get User Id in node and angular .

Code :

Node

router.get('/:id/api/data.json', function(req, res, next) {
    console.log(req.params.id);
    var userId = req.params.id;
    User.findById({_id:userId}, function (err, doc) {
        if (err) throw err
        if (doc){
            res.json({
                doc: doc,
                userID:req.params.id
                });
        }
    });
});

Angular :

 app.controller('profileCtrl', function($scope, $http) {
    $http.get("don't know how to get id from node").then(function (response) {
        console.log(response.data);
    });
});

Upvotes: 0

Views: 676

Answers (1)

aikorei
aikorei

Reputation: 580

Your Node.js router is listening to the url /:id/api/data.json. The :id part of that means Node.js is expecting a paramater there, which will get picked up by req.params.id in your Node.js file.

This means that you actually have to be passing in an id value as a part of the url. So your url would look something like /userid12345/api/data.json.

In your Angular file, that's the url you're going to be making the get request to. Which means you need to know the user's ID in your Angular file so you can get that specific url, e.g.:

var userId = 'userid12345';

$http.get('/' + userId + '/api/data.json').then(function(response) {
    console.log(response);
});

Once you pass userId in as a part of the url, then Node can grab it using req.params.id and you can make your db call.

Upvotes: 1

Related Questions