为何在Angular中使用App.run()以及在何处使用 [英] Why and where App.run() is used in Angular

查看:73
本文介绍了为何在Angular中使用App.run()以及在何处使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在大多数情况下,我会看到未使用 angular.module('',[]).run().这是否意味着在内部使用角度调用?

So in most instances, I see angular.module('', []).run() not being used. Does that mean angular calls it internally?

如果使用为什么?如果可能的话,请提供一个简单的用例,以帮助我理解该功能的必要性.

If used why? If possible please provide a simple use case for me to understand the necessity of the function.

推荐答案

模块是配置和运行块的集合,这些块可以在引导过程中应用于应用程序.在其最简单的形式,该模块由两种类型的集合组成方块:

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consists of a collection of two kinds of blocks:

  • 配置块-在提供者注册期间执行和配置阶段.只能注入提供者和常量进入配置块.这是为了防止意外实例化在完全配置服务之前进行操作.

  • Configuration blocks - 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 - 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.

因此AngularJS有两个主要的引导阶段,每个阶段分为两个子阶段:

So AngularJS has two main stages of bootstrapping each split in two sub stages:

  • 配置
  • 正在运行"
  • 编译和绑定
  • 第一个摘要循环

您可以订阅每个.要预订 run 阶段,请使用模块的 run 方法.在AngularJS解析DOM和编译组件之前以及在第一个变更检测周期之前,该阶段可用于执行一些逻辑.

You can subscribe to each of them. To subscribe to the run phase you use run method of the module. This phase can be used to perform some logic before AngularJS parses the DOM and compiles components and before first change detection cycle.

例如,您可以在将服务注入任何组件之前对其进行初始化:

For example, you can initialize a service before it's injected in any component:

angular.module('mymodule').run(function (MyService) {
    MyService.init();
});

如果您不订阅 run 阶段,AngularJS不会做任何特别的事情.根本没有任何功能被触发.

If you don't subscribe to the run phase, AngularJS doesn't do anything special. Simply no function is triggered.

这篇关于为何在Angular中使用App.run()以及在何处使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆