我想使用Angular从我的前端访问经过身份验证的用户数据。
这是Express on Node.js的回复。
exports.build = function (req, res) {
res.render('dashboard', {
uid: req.user._id
});
};
我目前通过uid
指令获取ng-init
。
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')
但是,我想避免这样做。
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);
});
};
}]);
我想将此uid
数据传递给Angular,而不必使用ng-init
指令。有没有办法访问响应数据,类似于:
console.log(res.body.uid);
从响应中检索uid
参数将不再需要ng-init
指令。我该如何检索它?
答案 0 :(得分:0)
更多,也许是优雅的解决方案是在URL中使用用户ID并映射路由以接受id
。
然后你的控制器看起来更像这个
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);
});
}]);