Sunday, 20 May 2018

How to Display Logged In User Details Using AngularJS

Hey! Good to see you!

Let's keep it simple this time. I would just give you:
  • the HTML code
  • the AngularJS Script

We would like to display the users Firstname, Lastname, email and Department

Then I would tell you the files you need to  include in your header.

File to Include in your Header
You need to include Bootstrap, JQuery and AngularJS in the header section of your html page




<script type="application/javascript" src="jquery.min.js"></script>  
<script type="text/javascript" src="bootstrap.js"> </script> 
<script type="application/javascript" src="angular.js"></script>
Listing 1: Header Files

AngularJS Script
The AngularJS script is given below. You need to enclose it in a <script></script>
tag.


var ShowUser = function(){
  $http({
  url: baseUrl + "api/user",  //The Base URL depends on your sharepoint server
  method: "GET",
  headers: { "Accept": "application/json; odata=verbose" }
  }).then(function mySucces(response) {
   $scope.DisplayName = response.data.First_Name + ', ' + response.data.Last_Name;
   $scope.Location = response.data.City;
   $scope.Department = response.data.Department;
   $scope.TotalPoints = 280;

 }, function error(response)  {
   console.log(response);
 });
};
Listing 2: AngularJS Script




The script retrieves the user's details from a the Request URL. Then it places the retrieved data in the $Scope variable. Data placed in the $Scope is accessible from the html page by using the {{}}  to enclose the variable name. That's all you need

The HTML Code
The HTML section that displays the  user details is given below. You can modify it to fit your page design.
 
<ul>
 <li>{{DisplayName}}</li>
 <li>{{Department}} </li>
 <li>{{Location}}</li>
</ul>
Listing 3: HTML Code

Make sure you try it and let me know if you have any challenges.
Thanks .