简体   繁体   中英

Angular.js - running a service function before anything else?

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.

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

plnkr = http://plnkr.co/edit/WTNuWKSgj0bMR1dtUkto?p=preview

The best way to configure how your services behave is to use providers. so, assuming you already have a mydata from your ajax call, the plnkr above shows a running example...

  myapp.config(['sayHelloProvider',function(sayHelloProvider){

    // assuming your ajax retrievies mydata
    var mydata = angular.fromJson(  angular.element(document.getElementById('mydata')).html() );

    // configure service
    sayHelloProvider.SetMessage("Olah! rate is=" + mydata.rate);


  }]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM