I am interested in accessing the information of the currently logged-in user

I am new to AngularJS and I am looking for help on retrieving information about the logged-in user. I want to be able to display this information but I'm not sure where to start. Here is my main Angular controller:

var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);

myApp.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'partials/main.html',
      access: {restricted: true}
    })
    // Other route definitions...
});

// Run function to handle route changes and user authentication check
myApp.run(function ($rootScope, $location, $route, AuthService) {
  $rootScope.$on('$routeChangeStart', function (event, next, current) {
    AuthService.getUserStatus().then(function(){
      if (next.access.restricted && !AuthService.isLoggedIn()){
        $location.path('/login');
        $route.reload();
      }
    });
  });
});

// Controller for handling meetups
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
  // Meetup resource initialization and query
}]);

// Controller for handling user data
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
  // User resource initialization and query
}]);

If anyone can provide some code examples or guidance, it would be greatly appreciated.

Answer №1

Angular utilizes Services for various functionalities, such as the Authentication Service provided below. Storing user information in local storage can help maintain user sessions even after closing the application.

 app.factory('AuthService', ['$q', '$http', 'LocalStorageService',
  function($q, $http, LocalStorageService) {
    var service = {};

    service.user = LocalStorageService.get("AUTH_USER", null);

    service.isLoggedIn = function(){
        return service.user != null && service.user != undefined && service.user != "";
    }

    service.checkLogged = function(){
        return $http.get(APPCONFIG.apiAccessPoint + "/user/" + service.user._id + "/isLogged").then(function(response){
            if(!response.data.success || !response.data.logged){
                service.logout();
                return false;
            }
            else{
                return true;
            }
        }, function(response){
            service.logout();
            return false;
        });
    }

    service.login = function(name, password){
        return $http.post(APPCONFIG.apiAccessPoint + "/user/login", {name: name, password: password}).then(function (response){
            if(response.data.success){ 
                LocalStorageService.set('AUTH_USER', response.data.data);
                $http.defaults.headers.common.Authorization = 'Bearer ' + response.data.data.token;
                service.user = response.data.data; 
            } 
            return response.data;
        }, function (response){
            if(response.status == 400 || response.data.error_code == "VAL_ERROR"){
                return response.data;
            }
            else{
                return $q.reject();
            }
        });
    }

    service.logout = function(){
        // remove token from local storage and clear http auth header
        LocalStorageService.deleteValue("AUTH_USER");
        $http.defaults.headers.common.Authorization = '';
        service.user = null;
    }

    return service;
}]);

To demonstrate how this service can be used in a controller (e.g., displaying a profile):

app.controller('ProfileViewCtrl', ['$scope', '$routeParams', 'AuthService', 'UserService',
function($scope, $routeParams, AuthService, UserService) {

     $scope.isLogged = AuthService.isLoggedIn();
     $scope.user = null;
     $scope.notFound = false;
     $scope.ownProfile = false;

     $scope.user = UserService.getUser($routeParams.user).then(function(response){
         if(response.success){
             $scope.user = response.data;
             $scope.notFound = response.data == undefined;
             if(!$scope.notFound && $scope.isLogged){
                 $scope.ownProfile = $scope.user._id == AuthService.user._id;
             }
         }
         else{
             console.log(response.data);
         }
     });


}]);

Alternatively, here's an example with a login page:

 app.controller('LoginCtrl', ['$scope', '$route', 'AuthService',
  function($scope, $route, AuthService) {

    $scope.user = {};

    $scope.login = function(){
        AuthService.login($scope.user.name, $scope.user.password).then(function(response){
            if(response.success){ 
                $route.reload();
            }
            else{
                console.log("Wrong User or password...");
            }
        });
    }
}]);    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Link an Object's Value to a Checkbox in Vue

My goal is to populate the array selectedParks with the value of each item. However, I am facing an issue where the value is always set to the string "item" instead of the actual value of the Park Object. Here is the code snippet: <ul class="list- ...

Opening a new window with Node-Webkit's start function

My application built on node-webkit has a control window and a separate presentation window. The control window collects data and triggers the opening of the presentation window using the window.open function. Once the presentation window is open, it can ...

Analyzing a problem with a table directive

Here is the custom directive code I have written: currentApp.directive('testList', ['$compile', function ($compile) { return{ restrict: 'E', template: '<table></table>', ...

best practices for passing variables between multiple files within a nodejs application

// script.js var mydata = 1 module.exports = {mydata}; // file in my codebase var newData = require("../script.js") console.log(newData.mydata); // why is it undefined? I want to declare a variable as global across the entire project. I tried using ...

Utilizing an Array of objects in conjunction with $.when

I have a list of Ajax requests stored in an Array, and I need to wait for all of them to finish loading before processing the results. Here is the code snippet I am currently using: $.when( RequestArray ).done(function(){ this.processResu ...

Using getJSON to return key/value pair from local host URL in JSFiddle - A step-by-step guide

After following a tutorial on building an API using Python, Flask, SQLite, and SQLAlchemy, I have successfully tested the connection by hitting the localhost address in my browser. Now, I am curious if it is possible to test this connection and see the des ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

`The logo does not dim when the popup is displayed`

I'm currently experiencing an issue with pop-ups on my page - when they appear, they create a shade over all elements of the page except for my two logos and are displayed with a border around them. Here's what my page looks like before the popu ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

What makes using setInterval with a self-invoking function a smarter choice?

I recently came across an explanation on how to properly use the setInterval() function. Essentially, it was mentioned that (function(){ // perform some actions setTimeout(arguments.callee, 60000); })(); ensures that the subsequent call from setTim ...

Tips for creating an onChange function in an input field using jQuery

I am looking to dynamically create inputs where each input has an `onChange` function with a variable. Here is my code: var distinct_inputs = 0; $('.icon1').click( function(){ distinct_inputs = distinct_inputs + 1 ; $('#insert-file&apo ...

Error: Unable to locate module 'react-calendar-heatmap'

After successfully creating a component that functioned flawlessly in my local application, I encountered an error when attempting to integrate it with npm: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:& ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

Apply CodeMirror theme and plugins using an HTML attribute

On my website, I have implemented a CodeMirror text area from . <form><textarea id="code" name="code" codemirror-type='lineNumbers: false, styleActiveLine: true, matchBrackets: true;'>CODE HERE</textarea></form> I added ...

The designated redirection path, as indicated in the 'next.config.js' file for a particular project, has now been applied to all projects

Something strange is happening... I set a redirect path for the root index page in one of my projects and it worked perfectly, but now all of my other projects are also being redirected to that same path when I try to visit localhost:3000. It's alway ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

Steps for Verifying the Legitimacy of an AJAX Request

In the process of creating a website where users are required to solve puzzles quickly, I am utilizing JavaScript to track the time taken for each puzzle. However, I am concerned about the possibility of users manipulating this data before it is sent to th ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Vue 3 has a known issue where scoped styles do not get applied correctly within the content of a <slot> element

Utilizing the Oruga and Storybook libraries for creating Vue 3 components. The code in the Vue file looks like this: <template> <o-radio v-bind="$props" v-model="model"> <slot /> </o-radio> </template ...