Invoking a shared controller function in AngularJS from a separate controller

My main objective is to retrieve the current logged-in user by calling back to the server when a visitor lands on the site while still logged in. The challenge I face is determining which controller will be active since it's uncertain which page the visitor will end up on.

Below is the User Service implementation:

app.factory('userService', function ($window) {
    var root = {};
    root.get_current_user = function(http){
        var config = {
            params: {}
        };
        http.post("/api/user/show", null, config)
            .success(function(data, status, headers, config) {
                if(data.success == true) {
                    user = data.user;

                    show_authenticated();
                }
            });
    };
    return root;
});

Here is an example of an empty controller where I'm trying to inject the user service:

app.controller('myResourcesController', function($scope, $http, userService) {

});

To initialize this process at the top of my index file, I would ideally have something like:

controller.get_current_user();

However, given that this needs to be executed across all pages, I am uncertain about the syntax to achieve this. Most examples found are specific to calling a particular controller, often from within another controller. It may be necessary to incorporate this logic within AngularJS itself rather than simply including it in a script tag on the index page.

Answer №1

To initialize your factory in Angular application, you can utilize the run method. Check out this resource for more information: https://docs.angularjs.org/guide/module#module-loading-dependencies

app.run(['userService', function(userService) {
  userService.get_current_user();
}]);

The userService factory should be responsible for storing the authenticated user object internally.

...
if (data.success == true) {
  root.user = data.user;
}
...

Once set up, you will be able to access your factory in any controller:

app.controller('myController', ['userService', function(userService) {
   //alert(userService.user);
}]);

Answer №2

To properly utilize $http in the factory constructor function, you must inject it first.

app.factory('userService', function ($window, $http) {
    var root = {};
    root.get_current_user = function(){
        var config = {
        params: {}
    };
    $http.post("/api/user/show", null, config)
        .success(function(data, status, headers, config) {
            if(data.success == true) {
                user = data.user;

                show_authenticated();
            }

        });
    };
    return root;
});

In your controller, you should use the following:

$scope.get_current_user = UserService.get_current_user();

You can also make use of ng attributes in your html as needed. If you require further assistance, please provide more details.

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

notify a designated channel when ready for launch

I'm currently attempting to figure out how to send a message to a channel when the Discord bot is launched. I've experimented with this code: client.on('message', (message) => { client.on('ready', () => { channel = cli ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

What is causing the delay in starting to play an audio track when it is clicked on?

I am facing an issue with my application and have created a minimum code example on StackBlitz to demonstrate the problem. The problematic code is also provided below. My goal is to have the Audio component play a track immediately when the user clicks on ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

Assistance needed with implementing jQuery tabs

I'm looking to add a link that takes me directly to content within a non-default tab on another page. Here's the code snippet that explains what I need: My Code: This is from my profile_edit.php page: The javascript: <script src="Javascrip ...

Unlocking the Secrets of JSON Data Retrieval

Could someone assist me in extracting data from the json provided below? I have received a json data in the following format, where each record contains "{0}". My query is how can I retrieve data from this format or if there is a way to remove "{0}" from ...

Unable to load models in face-api.js even though attempting to infer the models

Currently, I am working on developing an application for face detection. However, I am encountering an error stating "SsdMobilenetv1 - load model before inference" despite loading the models. The Front End HTML File is being sent from the server, ...

Turning my dual button navigation into tabs to display distinct HTML pages beneath a designated header

body{ background:url(background.jpg); background-size: cover; } h1{ font-family: 'Dancing Script', cursive; font-size: 5em; color: white; text-align: center; margin-top: 25px; margin-bottom: 20px; } h2{ font-size: 18px; color: white; text-align ...

How can I use CSS to ensure that both cards and images are equal in size?

I am currently utilizing react, with Material-ui being used for the Cards. For the layout, I have implemented CSS Grid Layout for the Grid system. Presently, the structure looks like this: https://i.stack.imgur.com/0FDyY.png However, my desired outcome i ...

Utilizing a button to trigger a directive nested within another directive?

My Angular code involves creating a div using the 'box1' directive, which contains a button. When this button is clicked, I need it to trigger another directive called 'box2', which should be inserted inside 'box1'. How can I ...

Setting up and customizing Express with Angular

Currently working on a straightforward Angular/Express todo-list app, I encountered some difficulties. As the project is still in progress, after running the code on localhost:3000, I noticed that {{ thing }} was displayed literally on the webpage. The di ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...

Leveraging Angular js for performing operations in Putty

At the moment, we depend on Putty for connecting to the app server and checking logs. I am looking for a solution that would allow me to automate this process using angular js. Is it possible to send commands from my angular js or any other client-side a ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. In contrast, highlighted near the red arrows is my attempt at using Winston to ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

React table row render error

I am facing an issue with my React code: var PostRow = React.createClass({ render: function(){ var loading = <tr><td>one row</td></tr>; return( {loading} ) } }); An error message is bein ...

Understanding the Importance and Benefits of Using the Classnames Utility in React Components

Can you break down for me the purpose of utilizing the Classnames utility in React code? I've reviewed the Classnames documentation, but I'm still struggling to comprehend why it is used in code like this: import classnames from 'classnames ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

The technique for accessing nested key-value pairs in a JSON object within an Angular application

After receiving the response from the backend, I have retrieved a nested hash map structure where one hash map is nested within another: hmap.put(l,hmaps); //hmap within hmap When returning the response to the frontend, I am using the ResponseEntity meth ...