How to get current user from sails into an angular view

809 Views Asked by At

I have gotten a list of users from my sails back end into an angular view using $http. However, all I need is the information of the current user, and I need to access each attribute individually. Can someone provide for me an example of how I might go about this?

1

There are 1 best solutions below

0
On BEST ANSWER

In api/controllers/UserController.js. This sails function returns the current user information in req.user.

   module.exports = {
     getUser: function(req,res) {
       return res.send(req.user);
};

In config/routes.js. This is the route to the 'getUser' function in UserController.js.

'/getUser': {
   controller: 'UserController',
   action: 'getUser'
}

In assets/js/controllers.js, here is the $http request to the 'getUser' function in UserController.js. This is how you get the information from req.user into the front end.

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;
  })
}]);

In assets/js/app.js, make sure your angular route is set to your view.

config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view', {templateUrl: 'partials/view.html', controller: 'myCtrl'});
}]);

After putting this code (with your own variables/routes/server info) in the correct places, you can access the current user in your view like this

<div ng-controller="myCtrl">
   {{ currentUser.email }} <br>
   {{ currentUser.username }} <br>
   {{ currentUser.etc }}
 </div>

I searched the internet high and low for a week for an answer on how to do this and eventually came up with this. I see that a lot of people (on this site especially) have asked the same question, and I never really found a good, explicit answer. So I thought I would post what I've come up with as an answer to my own question.