Ways to implement the Run function prior to any controller execution

Currently, I am exploring AngularJS to develop my very first application. My main goal is to ensure that the run function is executed before any controller.

Here's a snippet of my run function:

.run(function ($rootScope, authentification) 
{    
    teamsFactory.sendAuthent().then(function(response) 
    {    
        $rootScope.authentdata = response.data;
    });
})

Within my service where authentication takes place:


teams.sendAuthent = function(DeviceID) {  
    return $http({
        method: "POST",
        url: "http://myserver.com/authentification",
        headers: {'X-SocialAPI-Service-Name': 'auth'}
    })
    .then(function(aResponse)
    {
        var deferred = $q.defer();
        deferred.resolve({ data: aResponse.data });
        return deferred.promise;   
    }); 
}

Furthermore, here is the controller where I utilize the rootScope data:

.controller('home', function($rootScope, $scope, $http) 
{
    alert($rootScope.authentdata.token);
})

Unfortunately, I'm encountering an issue where it states that `autehndata` is undefined. It seems like the controller is being executed before the run function. How can I resolve this problem?

Answer №1

If you're looking for a solution, consider this suggestion:

$rootScope.$watch('authentdata', function(newVal, oldVal) {
    if(angular.isDefined(newVal) {
        alert($rootScope.authentdata.token);
        // Alternatively, you can use alert(newVal.token);
    }
}

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

Selecting objects within a small three.js view

I am able to showcase an entire page filled with graphical elements using three.js and can even select objects by clicking on them. However, when attempting to display three.js graphics in a small viewport within an HTML page, issues arise. In order to ca ...

Tips for efficiently calling a function without the need to check if it exists beforehand

I'm looking for a way to access the formik props outside of the form without constantly checking if a function exists before calling it when using refs. Any suggestions on how to achieve this? function BasicInfo({ event, initialValues, onSubmi ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

The issue with logging out feature

Operating an ASP.NET Web application, I have a Logout feature implemented in JavaScript. However, my current code closes the browser upon Logout, which is not the desired behavior. Instead, I am looking to clear cookies/session and redirect the user to the ...

Transmit information from the main directive to the subordinate directive

Hi everyone, I have a quick question.. I'm working on a directive that includes an ng-repeat and transclude, with several child directives inside it that need to inherit specific objects from each iteration... So far, I've only managed to achiev ...

Another option instead of using useCallback

Forgive me if this is a novice inquiry, but I am still learning JavaScript and React. I recently discovered the necessity of utilizing useCallback to wrap callback functions in order to prevent them from being recreated constantly when used within a fun ...

Guide to executing a chain of parallel API calls with changing parameters using nodejs

I am working on a project that involves making multiple API calls while changing a single parameter value in the URL based on values stored in an array. Currently, I have about 30-40 values in the array and I am using NodeJS and Express for this task. Belo ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Retrieving a PHP script from within a DIV element

I am seeking assistance to successfully load a PHP file from a DIV call. Below is the code I have used: <html> <head> </head> <body> <script class="code" type="text/javascript"> $("#LoadPHP").load("fb_marketing ...

command that fails to execute when a user is tagged

I've been working on a code snippet that generates a Rich Embed displaying the Avatar of a mentioned user or the message author if there is no mention. The interesting thing is, the code functions properly without a mention, but fails to work when men ...

What is the procedure for updating Angular services and directives?

I am working on a project where I need to integrate a slider with an external web service in order to send and receive data. To achieve this, I have developed a JSONP Angular service along with several directives that rely on this service. Can someone adv ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

ways to verify ng-if post modification occurrence

Currently, my project is utilizing Angular 6. In the code, there is a div element with *ng-if="edited" as shown below: <div *ngIf="edited"> {{langText}} </div> Initially, when the page loads, edited is set to false and the div is not vis ...

Automatically trigger a page reload using a jQuery function

Currently facing an issue with jQuery. I created a drop-down menu and would like it to expand when the li tag within the menu is clicked. Even though I am using the jQuery click function successfully, there seems to be a problem where the webpage refreshe ...

I'm attempting to make this script function correctly when an image is loaded

Can anyone help me figure out how to make this script function on image load instead of onclick? I came across the script on stackoverflow, but it was originally set up for onclick. I want it to work for onload or .load HTML====== <div id="contai ...

Creating a Vibrant Progress Bar with Multiple Colors: A Step-by-Step Guide

I'm still getting the hang of things, so I apologize if my question isn't perfectly clear. What I'm trying to do is create a dynamic progress bar with multiple colors that animates upon loading the page. I've seen some examples similar ...

Iterate over the JSON data file using ng-repeat to access the specific unique identifier

I am facing difficulties in iterating over a JSON file. I want to use ng-repeat to loop through the data array, ensuring that each field has a unique id. var fullData = { data: [{ 505: { price: "505", source: "Amazon" ...

Dealing with multiple JSON objects and organizing them into an array

After making an ajax call, I receive a response consisting of multiple JSON objects. // Sample response from ajax call: {"name":"suresh","class":"10th"},{"name":"suresh","class":"10th"} I am looking for assistance in splitting these objects and storing t ...

Navigating the root path that is defined in the gulp task within an Angular application

My current task involves building my application with the following code: const app = new Metalsmith(config.styleguide.path.root); app.use( msDefine({ production: false, rootPath: '/' }) ); app.use( ms ...