I want to access an authenticated user's data from my front-end using Angular.
This is the response from Express on Node.js.
exports.build = function (req, res) {
res.render('dashboard', {
uid: req.user._id
});
};
I grab the uid through the ng-init directive, currently.
doctype html
html
head
title= title
link(href='//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css', rel='stylesheet')
link(rel='stylesheet', href='/stylesheets/style.css')
block styles
body(ng-app='App', ng-controller='MainCntrl', ng-init='setUId(#{JSON.stringify(uid)})')
// some content
script(src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js')
script(src='//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js')
script(src='//cdnjs.cloudflare.com/ajax/libs/q.js/1.0.1/q.js')
script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js')
script(src='/javascripts/ng-app.js')
However, I would like to avoid doing this.
var app = angular.module('App', []);
app.factory('User', function () {
return {
// Promise for retrieving JSON User data
getProperties : function (id) {
var deferred = Q.defer();
$.getJSON('/api/user/' + id
, function (data) {
deferred.resolve(data);
}).fail(function () {
deferred.reject(true);
});
return deferred.promise;
}
};
});
app.controller('MainCntrl', ['$scope', '$http', 'User', function ($scope, $http, User) {
$scope.uid, $scope.user;
$scope.setUId = function (id) {
$scope.uid = id;
};
$scope.initUser = function () {
User.getProperties($scope.uid).then(function (user) {
$scope.$apply(function () {
$scope.user = user;
});
}, function (err) {
console.log(err);
});
};
}]);
I would like to pass this uid data to Angular without having to use the ng-init directive. Is there a way to access the response data, something along the lines of:
console.log(res.body.uid);
Retrieving the uid param from the response would remove the need for the ng-init directive. How would I go about retrieving it?
A more, and perhaps elegant solution would be to have the User ID in the URL and map a route to accept an id.
Then your controller can look more like this
app.controller('MainCntrl', ['$scope', '$http', 'User','$stateParams', function ($scope, $http, User, $stateParams) {
// NOTE: I do not know which route engine you're using, though you would inject
// its parameters provider in here, to get access to the url parameter (userId) of the route
// so for this example, i have assumed ng-router hence the injection of $stateParams
// the getProperties() method here is assuming ng-routet
User.getProperties($stateParams.id).then(function (user) {
$scope.user = user;
}, function (err) {
console.log(err);
});
}]);