Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  47] [ 2]  / answers: 1 / hits: 5716  / 10 Years ago, fri, september 12, 2014, 12:00:00

Can you run an Angular service (or a function on that service) before anything else? Ideally, as soon as ng-app gets parsed.



Here's my use case: I'm writing an app that gets AJAX data from a server and then parses the data a hundred different ways. I would like to make the initial AJAX call before all the controllers get called? That way I just have all the data parsed and loaded in the service without me worrying about updating any controllers or whatever.


More From » ajax

 Answers
16

I would like to make the initial AJAX call before all the controllers get called



In Angular method run is fired before any controller is called


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

app.run(function($rootScope){
// ajax call and other stuff
}

In run method you can do any job like login to Facebook, token validation and so on




Reference



Configuration blocks (aka app.config) - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.


Run blocks (aka app.run) - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.



docs.angularjs.org/guide/module


[#42549] Thursday, September 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;