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

Can we utilize conditions to both select and deselect items using JavaScript and PHP together?

I have a selection list with checkboxes that is dynamically generated based on certain conditions in the code snippet below. if ($data_inteiro_01 <= $data_inteiro_02) { if ($parcela[$i] === 0) { $display = 'disabled'; } } els ...

Do you think this architecture is ideal for a NodeJS recursive MongoDB archiver?

Currently, I am faced with the challenge of archiving data stored on a MongoDB server that has been operational for more than a year. The server has accumulated close to 100GB of data, with many collections containing over 10 million documents each. Unfort ...

Ways to implement a single AJAX function for multiple buttons

I need to call the same AJAX function for multiple buttons. Please assist with the code provided below. This particular code will create buttons and upon clicking on them, it displays details... please assist with resolving this issue. The code generated ...

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

Difficulty in adjusting the height of the popover menu that appears when using the Select Validator in Material UI

I am having trouble adjusting the height of a popover that emerges from a select validator form in Material UI. Despite attempting various methods, including adding the following CSS to the main class: '& .MuiPopover-paper': { height: &apos ...

Check the browser's developer tools to access JavaScript files

I recently came across a server at example.noodles.com that is hosting a node.js application. I'm curious if there's a way to access the source files of this application using inspect element or some other method? Up to now, all I've been a ...

How can one access the owner function from a different function?

Check out the example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/ (function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the c ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...

Optimal Approach for Managing Files in JavaScript

I have successfully uploaded a JSON file to my server using NodeJS and the 'http' module. Utilizing the NPM package 'formidable', I was able to save the file sent by the user onto the server. My next goal is to extract information from ...

Email attachments not working in Node Mailgun

I am facing an issue with my code that is designed to send emails using Mailgun in Node. The code functions as expected and sends the email successfully; however, it fails to attach the specified files. // pdfA and pdfB are both buffers defined earlier le ...

Leveraging JavaScript for pricing calculations within asp.net framework

I am currently working with a textbox in a gridview and trying to calculate values using JavaScript. My code seems to be error-free. The goal is to multiply the quantity by the rate to get the total price. function totalise(price, rate, qt) { var qt ...

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

Error: Attempting to subscribe to a post request returned a null result

Every time I attempt to subscribe to a post request, the TypeError: result is null is returned My setup involves an Angular CLI connecting with a Spring Boot application for a simple login page. My goal is to save the response header in local storage. Be ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

Removing JSON data with JavaScript

Currently, I am working on developing a custom discord bot for a server that I share with some friends. The bot includes a warn system and level system, and I have successfully implemented JavaScript to write data to an external JSON file. { "othe ...

What could be causing the JSF ajax status success to fail in Chrome?

Whenever I trigger an action in my ManagedBean, I also initiate a JavaScript function via JSF ajax to display a loading popup while the action is being processed. This functionality works flawlessly in Firefox, however, it seems to encounter issues in Chro ...

Online application for saving a vast quantity of information on the user's device

Is there a way for a web application to store an extensive amount of data client-side, allowing for millions of records to be accessed offline by users exclusively on Chrome? I initially considered indexedDb, but I discovered it becomes almost unusable wi ...

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...