简体   繁体   English

Angular.js - 在其他任何事情之前运行服务功能?

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

Can you run an Angular service (or a function on that service) before anything else ? 你能在其他任何事情之前运行Angular服务(或该服务的功能)吗? Ideally, as soon as ng-app gets parsed. 理想情况下,只要ng-app被解析。

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. 这是我的用例:我正在编写一个从服务器获取AJAX数据的应用程序,然后以一百种不同的方式解析数据。 I would like to make the initial AJAX call before all the controllers get called? 我想在调用所有控制器之前进行初始的AJAX调用? 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 我想在调用所有控制器之前进行初始的AJAX调用

In Angular method run is fired before any controller is called 在Angular方法中,在调用任何控制器之前触发run

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 run方法中,您可以执行任何工作,如登录Facebook,令牌验证等


Reference 参考

Configuration blocks (aka app.config) - get executed during the provider registrations and configuration phase. 配置块 (也称为app.config) - 在提供程序注册和配置阶段执行。 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. 运行块 (又名app.run) - 在创建注入器后执行并用于启动应用程序。 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 docs.angularjs.org/guide/module

plnkr = http://plnkr.co/edit/WTNuWKSgj0bMR1dtUkto?p=preview 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... 所以,假设你已经有一个来自你的ajax调用的mydata,上面的plnkr显示了一个正在运行的例子......

  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);


  }]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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