What is the best way to distribute login information across multiple controllers?

Currently, I am facing a challenge with my MainController and ChatController. Users log in using parameters like username, password, and jobname which are controlled by the MainController. However, in the ChatController, I still require the parameter jobname and I am unsure of how to pass it to the ChatController.

I attempted to write methods 'saveJobname' and 'getJobname' in the Auth service. Surprisingly, while getJobname functions properly, saveJobname does not work as expected, as indicated by the console.log(..) statement in the ChatController.

Below are some snippets of relevant code:

 // ---------------------MainController--------------------
app.controller('MainController', ['Auth', '$scope', '$window', '$rootScope', function(Auth, $scope, $rootScope, $window) {

  $scope.info = Auth.info;
  var vm = this;
  vm.loginData = {};

  vm.doLogin = function() {
    // ...login processing

    Auth
      .login(vm.loginData.username, vm.loginData.password)
      .success(function(data) {

        // ...some more code here

        if (data.success) { // if login successfully, then save jobname
          $scope.info.myjobname = vm.loginData.jobname;
          //Auth.saveJobname(vm.loginData.jobname); //does NOT work either

          // ...some more codes here

          $window.location.href = $window.location.href + '/../job.html';
        }
      });
  };
}]);



// --------------------ChatController----------------------
app.controller('ChatController', ['Auth', ChatController]);

function ChatController(Auth) {
  // ...come other codes here;
  console.log(Auth.info.myjobname); // it prints 'hello.world!' but not 'vm.loginData.jobname';
  // ...come other codes here;
}



// ------------------- AuthService ------------------------
app.factory('Auth', function($http, $q) {
  var authFactory = {};
  authFactory.info = {
    myjobname: 'hello.world!'
  };

  // get the API from auth.post('/login', function(...){...})
  authFactory.login = function(username, password) {

    return $http.post('http://localhost:8080/auth/login', {

      username: username,
      password: password

    }).success(function(data) {
      //some code here about token processing
      return data;
    });
  };

  authFactory.saveJobname = function(jobname) {
    authFactory.info.myjobname = jobname;
  };

  authFactory.getJobname = function() {
    return authFactory.info.myjobname;
  };

  return authFactory;
});

I would appreciate solutions that do not involve $rootScope. Please provide your insights and guidance.

Thank you very much.

Answer №1

To enhance the functionality of the Auth factory, you can include a new variable named authFactory.info = {}. This variable allows you to define important details such as username, password, and myjobname.

When utilizing these variables, simply bind the info object within your controller:

$scope.info = Auth.info

The revised Auth factory should be structured as follows:

// AuthService
app.factory('Auth', function($http, $q) {

  var authFactory = {};
  authFactory.info = {
    myjobname: 'hello.world!'
  };
  
  // Method for user login
  authFactory.login = function(username, password) {

    return $http.post('http://localhost:8080/auth/login', {

      username: username,
      password: password

    }).success(function(data) {
      // Code related to token processing can be added here
      return data;
    });
  };

  // Function to save jobname
  authFactory.saveJobname = function(jobname) {
    authFactory.info.myjobname = jobname;
  };

  // Function to retrieve jobname
  authFactory.getJobname = function(){
    return authFactory.info.myjobname;
  };

  return authFactory;
});

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

Preventing reference problems with AngularJS by employing the "copy()" method

I have a situation where I need to display a list of items with an "edit" button next to each one. When the user clicks on the edit button, an Angular UI modal window opens allowing them to make changes to the item. The problem I encountered was that any c ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

The interconnected nature of multiple asynchronous tasks can lead to a render loop when relying on each other, especially when

My asynchronous function fetches data in JSON format from an API, with each subsequent call dependent on the previously returned data. However, there are instances where I receive null values when trying to access data pulled from the API due to the async ...

Premature audio cutoffs in Javascript/CSS when using onmousedown event

One issue I'm facing is that a small beep sound should play when clicking on a link, but it gets cut off unless the click is held down. <script> var beep = new Audio(); beep.src = "audio/select.mp3"; </script> <div cla ...

How to Traverse Through Every Element in a For Loop with NodeJS

I am currently working on developing a full-stack application using Express and Mongoose on the backend. To better illustrate my goal, I will provide an image to give you a clearer understanding. https://i.sstatic.net/T5x8C.png The issue I am facing is d ...

The function .click does not function properly when used with an anchor element within a figure tag

In my JavaScript-loaded figure, there is an image description and two buttons. Sometimes the description contains a link with a fig attribute, like this: <a fig="allow" href="#tt5">[1]</a> If the anchor is not in a figure and has a fig attrib ...

Exclusively for Numerical Input with Number Keys

A customer on a website requires a Zip Code field that only accepts 5-digit numbers and triggers the numeric keypad on iOS and Android devices. It should also be compatible with external number pads on laptops. I've tried various approaches like keyC ...

Encountering a roadblock while trying to work with AngularJS Material radio buttons

In one of my projects, I have implemented a polling system where users can choose a question from a list and then proceed to the options page. On the options page, users can select their answer choices and submit their responses. The results are then displ ...

What is the best way to execute two asynchronous operations simultaneously in Node.js, treating them as a single atomic operation?

In my current setup, I have a function that calls two asynchronous functions. This main function is responsible for handling user requests. Let me show you an example: mainFunction(req, res, done) { asyncExist(req, function(exists) { if (!exists ...

Difficulty in locating elements within ngView-loaded elements using jQuery [AngularJS]

I am attempting to retrieve the offset().top of an element <div class='profile'></div> located within a ngView controlled by app.js. However, I encounter an error in the console: Uncaught TypeError: Cannot read property 'top&a ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Validating the same input in Angular Formly allows for consistent and

I am looking to create a validation process in Formly that ensures two input fields (both for email) return the same value. Currently, I have successfully implemented a check that compares the input field's value with the email field. vm.fields = [ ...

In Nodejs, there is a way to determine the size of a document stored

I have a question: How can I determine the size of a cursor, in terms of kilobytes (KB), without actually fetching it? I've come across various sources, such as this post on Stack Overflow, but I don't want to retrieve the query result just to f ...

Is it possible to specify the timing for executing Typescript decorators?

One issue I've encountered is that when I define a parameterized decorator for a method, the decorator runs before the method itself. Ideally, I'd like the decorator to run after the method has been called. function fooDecorator(value: boolean) ...

The object is visible on the front end but fails to transfer to the back end

Feeling a bit frustrated here because I've been struggling with this issue for over an hour now. I'm trying to compare a password input with the data stored in the database, but no matter what I do, I keep getting an empty object when sending the ...

What is the best way to produce a random integer within the range of 0 and 2

Here is the code snippet: var i = prompt('Please choose Rock, Paper or Scissors:'); var b = ['Rock', 'Paper', 'Scissors']; Now, I need help in generating a random number between 0-2. My initial idea was to do t ...

Exploring methods to identify visible elements within a div container using Angular 2

Seeking a solution to detect visible elements within a dynamically scrolled container that contains data of varying heights. Utilizing Angular 8 framework for development. html example: <div id="container" style="height: 300px; overflow-y: scroll"> ...

What could be causing the RxJS Observable to malfunction within a Vue.js app container?

Can anyone explain why the RxJS Observable in the "whatever" div is functioning properly, while the one in the app div for Vue.js is not working? (I am aware of modules that can bridge the gap between Vue.js and RxJS on NPM, but I am curious about why the ...

Uploading a binary file and its corresponding name simultaneously using AngularJS and Flask

I am currently struggling with uploading a file and its filename simultaneously in an angular request, then receiving it in Flask to save on disk. The file is being read from the local disc using: reader.readAsArrayBuffer(importData.ruleFile.files[0]); T ...

Having difficulty choosing an item from a personalized autocomplete search bar in my Vue.js/Vuetify.js project

NOTE: I have opted not to use v-autocomplete or v-combobox due to their limitations in meeting my specific requirements. I'm facing difficulties while setting up an autocomplete search bar. The search functionality works perfectly except for one mino ...