在 api/controllers/UserController.js 中。这个sails函数返回req.user中的当前用户信息。
module.exports = {
getUser: function(req,res) {
return res.send(req.user);
};
在 config/routes.js 中。这是 UserController.js 中“getUser”函数的路径。
'/getUser': {
controller: 'UserController',
action: 'getUser'
}
在 assets/js/controllers.js 中,这里是对 UserController.js 中“getUser”函数的 $http 请求。这是您从 req.user 获取信息到前端的方式。
angular.module('myApp.controllers', []).
controller('myCtrl', ['$scope', '$http', function($scope, $http) {
$http.get("http://localhost:1337/user/getUser").then(function(result) {
$scope.currentUser = result.data;
})
}]);
在 assets/js/app.js 中,确保您的角度路线设置为您的视图。
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view', {templateUrl: 'partials/view.html', controller: 'myCtrl'});
}]);
将此代码(带有您自己的变量/路由/服务器信息)放在正确的位置后,您可以像这样访问视图中的当前用户
<div ng-controller="myCtrl">
{{ currentUser.email }} <br>
{{ currentUser.username }} <br>
{{ currentUser.etc }}
</div>
我在互联网上搜索了一周的高低,以寻找有关如何执行此操作的答案,并最终想出了这个。我看到很多人(尤其是在这个网站上)都问过同样的问题,但我从来没有真正找到一个好的、明确的答案。所以我想我会发布我想出的内容作为我自己问题的答案。