155 KiB
Upgrading from AngularJS to Angular
从 AngularJS 升级到 Angular
Angular is the name for the Angular of today and tomorrow.
AngularJS is the name for all 1.x versions of Angular.
Angular 这个名字专指现在和未来的 Angular 版本,而 AngularJS 专指 Angular 的所有 1.x 版本。
AngularJS apps are great. Always consider the business case before moving to Angular. An important part of that case is the time and effort to get there. This guide describes the built-in tools for efficiently migrating AngularJS projects over to the Angular platform, a piece at a time.
有很多大型 AngularJS 应用。 在决定迁移到 Angular 之前,首先要深入思考业务案例。 在这些案例中,最重要的部分之一是时间和需要付出的努力。 本章描述用于把 AngularJS 应用高效迁移到 Angular 平台的内置工具,每次讲一点点。
Some applications will be easier to upgrade than others, and there are many ways to make it easier for yourself. It is possible to prepare and align AngularJS applications with Angular even before beginning the upgrade process. These preparation steps are all about making the code more decoupled, more maintainable, and better aligned with modern development tools. That means in addition to making the upgrade easier, you will also improve the existing AngularJS applications.
有些应用可能比其它的升级起来简单,还有一些方法能让把这项工作变得更简单。 即使在正式开始升级过程之前,可以提前准备 AngularJS 的程序,让它向 Angular 看齐。 这些准备步骤几乎都是关于如何让代码更加松耦合、更有可维护性,以及用现代开发工具提高速度的。 这意味着,这种准备工作不仅能让最终的升级变得更简单,而且还能提升 AngularJS 程序的质量。
One of the keys to a successful upgrade is to do it incrementally,
by running the two frameworks side by side in the same application, and
porting AngularJS components to Angular one by one. This makes it possible
to upgrade even large and complex applications without disrupting other
business, because the work can be done collaboratively and spread over
a period of time. The upgrade
module in Angular has been designed to
make incremental upgrading seamless.
成功升级的关键之一是增量式的实现它,通过在同一个应用中一起运行这两个框架,并且逐个把 AngularJS 的组件迁移到 Angular 中。
这意味着可以在不必打断其它业务的前提下,升级更大、更复杂的应用程序,因为这项工作可以多人协作完成,在一段时间内逐渐铺开。
Angular upgrade
模块的设计目标就是让你渐进、无缝的完成升级。
Preparation
准备工作
There are many ways to structure AngularJS applications. When you begin to upgrade these applications to Angular, some will turn out to be much more easy to work with than others. There are a few key techniques and patterns that you can apply to future proof apps even before you begin the migration.
AngularJS 应用程序的组织方式有很多种。当你想把它们升级到 Angular 的时候, 有些做起来会比其它的更容易些。即使在开始升级之前,也有一些关键的技术和模式可以让你将来升级时更轻松。
{@a follow-the-angular-styleguide}
Follow the AngularJS Style Guide
遵循 AngularJS 风格指南
The AngularJS Style Guide collects patterns and practices that have been proven to result in cleaner and more maintainable AngularJS applications. It contains a wealth of information about how to write and organize AngularJS code - and equally importantly - how not to write and organize AngularJS code.
AngularJS 风格指南收集了一些已证明能写出干净且可维护的 AngularJS 程序的模式与实践。 它包含了很多关于如何书写和组织 AngularJS 代码的有价值信息,同样重要的是,不应该采用的书写和组织 AngularJS 代码的方式。
Angular is a reimagined version of the best parts of AngularJS. In that sense, its goals are the same as the AngularJS Style Guide's: To preserve the good parts of AngularJS, and to avoid the bad parts. There's a lot more to Angular than just that of course, but this does mean that following the style guide helps make your AngularJS app more closely aligned with Angular.
Angular 是一个基于 AngularJS 中最好的部分构思出来的版本。在这种意义上,它的目标和 AngularJS 风格指南是一样的: 保留 AngularJS 中好的部分,去掉坏的部分。当然,Angular 还做了更多。 说这些的意思是:遵循这个风格指南可以让你写出更接近 Angular 程序的 AngularJS 程序。
There are a few rules in particular that will make it much easier to do
an incremental upgrade using the Angular upgrade/static
module:
有一些特别的规则可以让使用 Angular 的 upgrade/static
模块进行增量升级变得更简单:
-
The Rule of 1 states that there should be one component per file. This not only makes components easy to navigate and find, but will also allow us to migrate them between languages and frameworks one at a time. In this example application, each controller, component, service, and filter is in its own source file.
单一规则 规定每个文件应该只放一个组件。这不仅让组件更容易浏览和查找,而且还让你能逐个迁移它们的语言和框架。 在这个范例程序中,每个控制器、工厂和过滤器都位于各自的源文件中。
-
The Folders-by-Feature Structure and Modularity rules define similar principles on a higher level of abstraction: Different parts of the application should reside in different directories and NgModules.
按特性分目录的结构和模块化规则在较高的抽象层定义了一些相似的原则:应用程序中的不同部分应该被分到不同的目录和 NgModule 中。
When an application is laid out feature per feature in this way, it can also be migrated one feature at a time. For applications that don't already look like this, applying the rules in the AngularJS style guide is a highly recommended preparation step. And this is not just for the sake of the upgrade - it is just solid advice in general!
如果应用程序能用这种方式把每个特性分到一个独立目录中,它也就能每次迁移一个特性。 对于那些还没有这么做的程序,强烈建议把应用这条规则作为准备步骤。而且这也不仅仅对升级有价值, 它还是一个通用的规则,可以让你的程序更“坚实”。
Using a Module Loader
使用模块加载器
When you break application code down into one component per file, you often end up with a project structure with a large number of relatively small files. This is a much neater way to organize things than a small number of large files, but it doesn't work that well if you have to load all those files to the HTML page with <script> tags. Especially when you also have to maintain those tags in the correct order. That's why it's a good idea to start using a module loader.
当你把应用代码分解到每个文件中只放一个组件的粒度后,通常会得到一个由大量相对较小的文件组成的项目结构。
这比组织成少量大文件要整洁得多,但如果你不得不通过 <script>
标签在 HTML 页面中加载所有这些文件,那就不好玩了。
尤其是当你不得不自己按正确的顺序维护这些标签时更是如此,就要开始使用模块加载器了。
Using a module loader such as SystemJS,
Webpack, or Browserify
allows us to use the built-in module systems of TypeScript or ES2015.
You can use the import
and export
features that explicitly specify what code can
and will be shared between different parts of the application. For ES5 applications
you can use CommonJS style require
and module.exports
features. In both cases,
the module loader will then take care of loading all the code the application needs
in the correct order.
使用模块加载器,比如SystemJS、
Webpack或Browserify,
可以让你在程序中使用 TypeScript 或 ES2015 语言内置的模块系统。
你可以使用 import
和 export
特性来明确指定哪些代码应该以及将会被在程序的不同部分之间共享。
对于 ES5 程序来说,可以改用 CommonJS 风格的 require
和 module.exports
特性代替。
无是论哪种情况,模块加载器都会按正确的顺序加载程序中用到的所有代码。
When moving applications into production, module loaders also make it easier to package them all up into production bundles with batteries included.
当要把应用程序投入生产环境时,模块加载器也会让你把所有这些文件打成完整的产品包变得容易一些。
Migrating to TypeScript
迁移到 TypeScript
If part of the Angular upgrade plan is to also take TypeScript into use, it makes sense to bring in the TypeScript compiler even before the upgrade itself begins. This means there's one less thing to learn and think about during the actual upgrade. It also means you can start using TypeScript features in your AngularJS code.
Angular 升级计划的一部分是引入 TypeScript,即使在开始升级之前,引入 TypeScript 编译器也是有意义的。 这意味着等真正升级的时候需要学习和思考的东西会更少,并且你可以在 AngularJS 代码中开始使用 TypeScript 的特性。
Since TypeScript is a superset of ECMAScript 2015, which in turn is a superset
of ECMAScript 5, "switching" to TypeScript doesn't necessarily require anything
more than installing the TypeScript compiler and renaming files from
*.js
to *.ts
. But just doing that is not hugely useful or exciting, of course.
Additional steps like the following can give us much more bang for the buck:
TypeScript 是 ECMAScript 2015 的超集,而 ES2015 又是 ECMAScript 5 的超集。
这意味着除了安装一个 TypeScript 编译器,并把文件名都从 *.js
改成 *.ts
之外,其实什么都不用做。
当然,如果仅仅这样做也没什么大用,也没什么有意思的地方。
下面这些额外的步骤可以让你打起精神:
-
For applications that use a module loader, TypeScript imports and exports (which are really ECMAScript 2015 imports and exports) can be used to organize code into modules.
对那些使用了模块加载器的程序,TypeScript 的导入和导出语法(实际上是 ECMAScript 2015 的导入和导出)可以把代码组织成模块。
-
Type annotations can be gradually added to existing functions and variables to pin down their types and get benefits like build-time error checking, great autocompletion support and inline documentation.
可以逐步把类型注解添加到现有函数和变量上,以固定它们的类型,并获得其优点:比如编译期错误检查、更好的支持自动完成,以及内联式文档等。
-
JavaScript features new to ES2015, like arrow functions,
let
s andconst
s, default function parameters, and destructuring assignments can also be gradually added to make the code more expressive.那些 ES2015 中新增的特性,比如箭头函数、
let
、const
、默认函数参数、解构赋值等也可以逐渐添加进来,让代码更有表现力。 -
Services and controllers can be turned into classes. That way they'll be a step closer to becoming Angular service and component classes, which will make life easier after the upgrade.
服务和控制器可以转成类。这样它们就能一步步接近 Angular 的服务和组件类了,也会让升级变得简单一点。
Using Component Directives
使用组件型指令
In Angular, components are the main primitive from which user interfaces are built. You define the different portions of the UI as components and compose them into a full user experience.
在 Angular 中,组件是用来构建用户界面的主要元素。你把 UI 中的不同部分定义成组件,然后在模板中使用这些组件合成出最终的 UI。
You can also do this in AngularJS, using component directives. These are
directives that define their own templates, controllers, and input/output bindings -
the same things that Angular components define. Applications built with
component directives are much easier to migrate to Angular than applications
built with lower-level features like ng-controller
, ng-include
, and scope
inheritance.
你在 AngularJS 中也能这么做。那就是一种定义了自己的模板、控制器和输入/输出绑定的指令 —— 跟 Angular 中对组件的定义是一样的。
要迁移到 Angular,通过组件型指令构建的应用程序会比直接用 ng-controller
、ng-include
和作用域继承等底层特性构建的要容易得多。
To be Angular compatible, an AngularJS component directive should configure these attributes:
要与 Angular 兼容,AngularJS 的组件型指令应该配置下列属性:
-
restrict: 'E'
. Components are usually used as elements.restrict: 'E'
。组件通常会以元素的方式使用。 -
scope: {}
- an isolate scope. In Angular, components are always isolated from their surroundings, and you should do this in AngularJS too.scope: {}
- 一个独立作用域。在 Angular 中,组件永远是从它们的环境中被隔离出来的,在 AngularJS 中也同样如此。 -
bindToController: {}
. Component inputs and outputs should be bound to the controller instead of using the$scope
.bindToController: {}
。组件的输入和输出应该绑定到控制器,而不是$scope
。 -
controller
andcontrollerAs
. Components have their own controllers.controller
和controllerAs
。组件要有自己的控制器。 -
template
ortemplateUrl
. Components have their own templates.template
或templateUrl
。组件要有自己的模板。
Component directives may also use the following attributes:
组件型指令还可能使用下列属性:
-
transclude: true/{}
, if the component needs to transclude content from elsewhere.transclude: true
:如果组件需要从其它地方透传内容,就设置它。 -
require
, if the component needs to communicate with some parent component's controller.require
:如果组件需要和父组件的控制器通讯,就设置它。
Component directives should not use the following attributes:
组件型指令不能使用下列属性:
-
compile
. This will not be supported in Angular.compile
。Angular 不再支持它。 -
replace: true
. Angular never replaces a component element with the component template. This attribute is also deprecated in AngularJS.replace: true
。Angular 永远不会用组件模板替换一个组件元素。这个特性在 AngularJS 中也同样不建议使用了。 -
priority
andterminal
. While AngularJS components may use these, they are not used in Angular and it is better not to write code that relies on them.priority
和terminal
。虽然 AngularJS 的组件可能使用这些,但它们在 Angular 中已经没用了,并且最好不要再写依赖它们的代码。
An AngularJS component directive that is fully aligned with the Angular architecture may look something like this:
AngularJS 中一个完全向 Angular 架构对齐过的组件型指令是这样的:
AngularJS 1.5 introduces the component API that makes it easier to define component directives like these. It is a good idea to use this API for component directives for several reasons:
AngularJS 1.5 引入了组件 API,它让定义指令变得更简单了。 为组件型指令使用这个 API 是一个好主意,因为:
-
It requires less boilerplate code.
它需要更少的样板代码。
-
It enforces the use of component best practices like
controllerAs
.它强制你遵循组件的最佳实践,比如
controllerAs
。 -
It has good default values for directive attributes like
scope
andrestrict
.指令中像
scope
和restrict
这样的属性应该有良好的默认值。
The component directive example from above looks like this when expressed using the component API:
如果使用这个组件 API 进行表示,那么上面看到的组件型指令就变成了这样:
Controller lifecycle hook methods $onInit()
, $onDestroy()
, and $onChanges()
are another convenient feature that AngularJS 1.5 introduces. They all have nearly
exact equivalents in Angular, so organizing component lifecycle
logic around them will ease the eventual Angular upgrade process.
控制器的生命周期钩子 $onInit()
、$onDestroy()
和 $onChanges()
是 AngularJS 1.5 引入的另一些便利特性。
它们都很像Angular 中的等价物,所以,围绕它们组织组件生命周期的逻辑在升级到 Angular 时会更容易。
Upgrading with ngUpgrade
使用升级适配器进行升级
The ngUpgrade library in Angular is a very useful tool for upgrading anything but the smallest of applications. With it you can mix and match AngularJS and Angular components in the same application and have them interoperate seamlessly. That means you don't have to do the upgrade work all at once, since there's a natural coexistence between the two frameworks during the transition period.
不管要升级什么,Angular 中的 ngUpgrade
库都会是一个非常有用的工具 —— 除非是小到没功能的应用。
借助它,你可以在同一个应用程序中混用并匹配 AngularJS 和 Angular 的组件,并让它们实现无缝的互操作。
这意味着你不用被迫一次性做完所有的升级工作,因为在整个演进过程中,这两个框架可以很自然的和睦相处。
How ngUpgrade Works
升级模块工作原理
One of the primary tools provided by ngUpgrade is called the UpgradeModule
.
This is a module that contains utilities for bootstrapping and managing hybrid
applications that support both Angular and AngularJS code.
ngUpgrade
提供的主要工具之一被称为 UpgradeModule
。这是一个服务,它可以启动并管理一个能同时支持 Angular 和 AngularJS 的混合式应用。
When you use ngUpgrade, what you're really doing is running both AngularJS and Angular at the same time. All Angular code is running in the Angular framework, and AngularJS code in the AngularJS framework. Both of these are the actual, fully featured versions of the frameworks. There is no emulation going on, so you can expect to have all the features and natural behavior of both frameworks.
当使用 ngUpgrade 时,你实际上在同时运行 AngularJS 和 Angular。所有 Angular 的代码运行在 Angular 框架中,而 AngularJS 的代码运行在 AngularJS 框架中。所有这些都是真实的、全功能的框架版本。 没有进行任何仿真,所以你可以认为同时存在着这两个框架的所有特性和自然行为。
What happens on top of this is that components and services managed by one framework can interoperate with those from the other framework. This happens in three main areas: Dependency injection, the DOM, and change detection.
所有这些事情的背后,本质上是一个框架中管理的组件和服务能和来自另一个框架的进行互操作。 这些主要体现在三个方面:依赖注入、DOM 和变更检测。
Dependency Injection
依赖注入
Dependency injection is front and center in both AngularJS and Angular, but there are some key differences between the two frameworks in how it actually works.
无论是在 AngularJS 中还是在 Angular 中,依赖注入都位于前沿和中心的位置,但在两个框架的工作原理上,却存在着一些关键的不同之处。
<th>
AngularJS
</th>
<th>
Angular
</th>
<td>
Dependency injection tokens are always strings
依赖注入的令牌(Token)永远是字符串(译注:指服务名称)。
</td>
<td>
Tokens [can have different types](guide/dependency-injection).
They are often classes. They may also be strings.
令牌[可能有不同的类型](guide/dependency-injection)。
通常是类,也可能是字符串。
</td>
<td>
There is exactly one injector. Even in multi-module applications,
everything is poured into one big namespace.
只有一个注入器。即使在多模块的应用程序中,每样东西也都会被装入一个巨大的命名空间中。
</td>
<td>
There is a [tree hierarchy of injectors](guide/hierarchical-dependency-injection),
with a root injector and an additional injector for each component.
这是一个[树状多层注入器](guide/hierarchical-dependency-injection):有一个根注入器,而且每个组件也有一个自己的注入器。
</td>
Even accounting for these differences you can still have dependency injection
interoperability. upgrade/static
resolves the differences and makes
everything work seamlessly:
就算有这么多不同点,也并不妨碍你在依赖注入时进行互操作。UpgradeModule
解决了这些差异,并让它们无缝的对接:
-
You can make AngularJS services available for injection to Angular code by upgrading them. The same singleton instance of each service is shared between the frameworks. In Angular these services will always be in the root injector and available to all components.
通过升级它们,你就能让那些在 AngularJS 中能被注入的服务也可用于 Angular 的代码中。 在框架之间共享的是服务的同一个单例对象。在 Angular 中,这些外来服务总是被放在根注入器中,并可用于所有组件。 它们总是具有字符串令牌 —— 跟它们在 AngularJS 中的令牌相同。
-
You can also make Angular services available for injection to AngularJS code by downgrading them. Only services from the Angular root injector can be downgraded. Again, the same singleton instances are shared between the frameworks. When you register a downgraded service, you must explicitly specify a string token that you want to use in AngularJS.
通过降级它们,你也能让那些在 Angular 中能被注入的服务在 AngularJS 的代码中可用。 只有那些来自 Angular 根注入器的服务才能被降级。同样的,在框架之间共享的是同一个单例对象。 当你注册一个要降级的服务时,要明确指定一个打算在 AngularJS 中使用的字符串令牌。
Components and the DOM
组件与 DOM
In the DOM of a hybrid ngUpgrade application are components and directives from both AngularJS and Angular. These components communicate with each other by using the input and output bindings of their respective frameworks, which ngUpgrade bridges together. They may also communicate through shared injected dependencies, as described above.
在混合式应用中,同时存在来自 AngularJS 和 Angular 中组件和指令的 DOM。
这些组件通过它们各自框架中的输入和输出绑定来互相通讯,它们由 UpgradeModule
桥接在一起。
它们也能通过共享被注入的依赖彼此通讯,就像前面所说的那样。
The key thing to understand about a hybrid application is that every element in the DOM is owned by exactly one of the two frameworks. The other framework ignores it. If an element is owned by AngularJS, Angular treats it as if it didn't exist, and vice versa.
理解混合式应用的关键在于,DOM 中的每一个元素都只能属于这两个框架之一,而另一个框架则会忽略它。如果一个元素属于 AngularJS,那么 Angular 就会当它不存在,反之亦然。
So normally a hybrid application begins life as an AngularJS application, and it is AngularJS that processes the root template, e.g. the index.html. Angular then steps into the picture when an Angular component is used somewhere in an AngularJS template. That component's template will then be managed by Angular, and it may contain any number of Angular components and directives.
所以,混合式应用总是像 AngularJS 程序那样启动,处理根模板的也是 AngularJS. 然后,当这个应用的模板中使用到了 Angular 的组件时,Angular 才开始参与。 这个组件的视图由 Angular 进行管理,而且它还可以使用一系列的 Angular 组件和指令。
Beyond that, you may interleave the two frameworks. You always cross the boundary between the two frameworks by one of two ways:
更进一步说,你可以按照需要,任意穿插使用这两个框架。 使用下面的两种方式之一,你可以在这两个框架之间自由穿梭:
-
By using a component from the other framework: An AngularJS template using an Angular component, or an Angular template using an AngularJS component.
通过使用来自另一个框架的组件:AngularJS 的模板中用到了 Angular 的组件,或者 Angular 的模板中使用了 AngularJS 的组件。
-
By transcluding or projecting content from the other framework. ngUpgrade bridges the related concepts of AngularJS transclusion and Angular content projection together.
通过透传(transclude)或投影(project)来自另一个框架的内容。
UpgradeModule
牵线搭桥,把 AngularJS 的透传概念和 Angular 的内容投影概念关联起来。
Whenever you use a component that belongs to the other framework, a switch between framework boundaries occurs. However, that switch only happens to the elements in the template of that component. Consider a situation where you use an Angular component from AngularJS like this:
当你使用一个属于另一个框架的组件时,就会发生一次跨框架边界的切换。不过,这种切换只发生在该组件元素的子节点上。 考虑一个场景,你从 AngularJS 中使用一个 Angular 组件,就像这样:
<a-component></a-component>The DOM element <a-component>
will remain to be an AngularJS managed
element, because it's defined in an AngularJS template. That also
means you can apply additional AngularJS directives to it, but not
Angular directives. It is only in the template of the <a-component>
where Angular steps in. This same rule also applies when you
use AngularJS component directives from Angular.
此时,<a-component>
这个 DOM 元素仍然由 AngularJS 管理,因为它是在 AngularJS 的模板中定义的。
这也意味着你可以往它上面添加别的 AngularJS 指令,却不能添加 Angular 的指令。
只有在 <a-component>
组件的模板中才是 Angular 的天下。同样的规则也适用于在 Angular 中使用 AngularJS 组件型指令的情况。
Change Detection
变更检测
The scope.$apply()
is how AngularJS detects changes and updates data bindings.
After every event that occurs, scope.$apply()
gets called. This is done either
automatically by the framework, or manually by you.
AngularJS 中的变更检测全是关于 scope.$apply()
的。在每个事件发生之后,scope.$apply()
就会被调用。
这或者由框架自动调用,或者在某些情况下由你自己的代码手动调用。
In Angular things are different. While change detection still
occurs after every event, no one needs to call scope.$apply()
for
that to happen. This is because all Angular code runs inside something
called the Angular zone. Angular always
knows when the code finishes, so it also knows when it should kick off
change detection. The code itself doesn't have to call scope.$apply()
or anything like it.
在 Angular 中,事情有点不一样。虽然变更检测仍然会在每一个事件之后发生,却不再需要每次调用 scope.$apply()
了。
这是因为所有 Angular 代码都运行在一个叫做Angular zone的地方。
Angular 总是知道什么时候代码执行完了,也就知道了它什么时候应该触发变更检测。代码本身并不需要调用 scope.$apply()
或其它类似的东西。
In the case of hybrid applications, the UpgradeModule
bridges the
AngularJS and Angular approaches. Here's what happens:
在这种混合式应用的案例中,UpgradeModule
在 AngularJS 的方法和 Angular 的方法之间建立了桥梁。发生了什么呢?
-
Everything that happens in the application runs inside the Angular zone. This is true whether the event originated in AngularJS or Angular code. The zone triggers Angular change detection after every event.
应用中发生的每件事都运行在 Angular 的 zone 里。 无论事件发生在 AngularJS 还是 Angular 的代码中,都是如此。 这个 zone 会在每个事件之后触发 Angular 的变更检测。
-
The
UpgradeModule
will invoke the AngularJS$rootScope.$apply()
after every turn of the Angular zone. This also triggers AngularJS change detection after every event.UpgradeModule
将在每一次离开 Angular zone 时调用 AngularJS 的$rootScope.$apply()
。这样也就同样会在每个事件之后触发 AngularJS 的变更检测。
In practice, you do not need to call $apply()
,
regardless of whether it is in AngularJS or Angular. The
UpgradeModule
does it for us. You can still call $apply()
so there
is no need to remove such calls from existing code. Those calls just trigger
additional AngularJS change detection checks in a hybrid application.
在实践中,你不用在自己的代码中调用 $apply()
,而不用管这段代码是在 AngularJS 还是 Angular 中。
UpgradeModule
都替你做了。你仍然可以调用 $apply()
,也就是说你不必从现有代码中移除此调用。
在混合式应用中,这些调用只会触发一次额外的 AngularJS 变更检测。
When you downgrade an Angular component and then use it from AngularJS, the component's inputs will be watched using AngularJS change detection. When those inputs change, the corresponding properties in the component are set. You can also hook into the changes by implementing the OnChanges interface in the component, just like you could if it hadn't been downgraded.
当你降级一个 Angular 组件,然后把它用于 AngularJS 中时,组件的输入属性就会被 AngularJS 的变更检测体系监视起来。 当那些输入属性发生变化时,组件中相应的属性就会被设置。你也能通过实现OnChanges 接口来挂钩到这些更改,就像它未被降级时一样。
Correspondingly, when you upgrade an AngularJS component and use it from Angular,
all the bindings defined for the component directive's scope
(or bindToController
)
will be hooked into Angular change detection. They will be treated
as regular Angular inputs. Their values will be written to the upgraded component's
scope (or controller) when they change.
相应的,当你把 AngularJS 的组件升级给 Angular 使用时,在这个组件型指令的 scope
(或 bindToController
)中定义的所有绑定,
都将被挂钩到 Angular 的变更检测体系中。它们将和标准的 Angular 输入属性被同等对待,并当它们发生变化时设置回 scope(或控制器)上。
Using UpgradeModule with Angular NgModules
通过 Angular 的 NgModule 来使用 UpgradeModule
Both AngularJS and Angular have their own concept of modules to help organize an application into cohesive blocks of functionality.
AngularJS 还是 Angular 都有自己的模块概念,来帮你把应用组织成一些内聚的功能块。
Their details are quite different in architecture and implementation.
In AngularJS, you add Angular assets to the angular.module
property.
In Angular, you create one or more classes adorned with an NgModule
decorator
that describes Angular assets in metadata. The differences blossom from there.
它们在架构和实现的细节上有着显著的不同。
在 AngularJS 中,你要把 AngularJS 的资源添加到 angular.module
属性上。
在 Angular 中,你要创建一个或多个带有 NgModule
装饰器的类,这些装饰器用来在元数据中描述 Angular 资源。差异主要来自这里。
In a hybrid application you run both versions of Angular at the same time.
That means that you need at least one module each from both AngularJS and Angular.
You will import UpgradeModule
inside the NgModule, and then use it for
bootstrapping the AngularJS module.
在混合式应用中,你同时运行了两个版本的 Angular。
这意味着你至少需要 AngularJS 和 Angular 各提供一个模块。
当你使用 AngularJS 的模块进行引导时,就得把 Angular 的模块传给 UpgradeModule
。
Bootstrapping hybrid applications
引导混合式应用程序
To bootstrap a hybrid application, you must bootstrap each of the Angular and
AngularJS parts of the application. You must bootstrap the Angular bits first and
then ask the UpgradeModule
to bootstrap the AngularJS bits next.
要想引导混合式应用,就必须在应用中分别引导 Angular 和 AngularJS 应用的一部分。你必须先引导 Angular,然后再调用 UpgradeModule
来引导 AngularJS。
In an AngularJS application you have a root AngularJS module, which will also be used to bootstrap the AngularJS application.
在 AngularJS 应用中有一个 AngularJS 的根模块,它用于引导 AngularJS 应用。
Pure AngularJS applications can be automatically bootstrapped by using an ng-app
directive somewhere on the HTML page. But for hybrid applications, you manually bootstrap via the
UpgradeModule
. Therefore, it is a good preliminary step to switch AngularJS applications to use the
manual JavaScript angular.bootstrap
method even before switching them to hybrid mode.
单纯的 AngularJS 应用可以在 HTML 页面中使用 ng-app
指令进行引导,但对于混合式应用你要通过 UpgradeModule
模块进行手动引导。因此,在切换成混合式应用之前,最好先把 AngularJS 改写成使用 angular.bootstrap
进行手动引导的方式。
Say you have an ng-app
driven bootstrap such as this one:
比如你现在有这样一个通过 ng-app
进行引导的应用:
You can remove the ng-app
and ng-strict-di
directives from the HTML
and instead switch to calling angular.bootstrap
from JavaScript, which
will result in the same thing:
你可以从 HTML 中移除 ng-app
和 ng-strict-di
指令,改为从 JavaScript 中调用 angular.bootstrap
,它能达到同样效果:
To begin converting your AngularJS application to a hybrid, you need to load the Angular framework. You can see how this can be done with SystemJS by following the instructions in Setup for Upgrading to AngularJS for selectively copying code from the QuickStart github repository.
要想把 AngularJS 应用变成 Hybrid 应用,就要先加载 Angular 框架。 根据准备升级到 AngularJS 中给出的步骤,选择性的把“快速上手”的 Github 仓库中的代码复制过来。
You also need to install the @angular/upgrade
package via npm install @angular/upgrade --save
and add a mapping for the @angular/upgrade/static
package:
也可以通过 npm install @angular/upgrade --save
命令来安装 @angular/upgrade
包,并给它添加一个到 @angular/upgrade/static
包的映射。
Next, create an app.module.ts
file and add the following NgModule
class:
接下来,创建一个 app.module.ts
文件,并添加下列 NgModule
类:
This bare minimum NgModule
imports BrowserModule
, the module every Angular browser-based app must have.
It also imports UpgradeModule
from @angular/upgrade/static
, which exports providers that will be used
for upgrading and downgrading services and components.
最小化的 NgModule
导入了 BrowserModule
,它是每个基于浏览器的 Angular 应用必备的。
它还从 @angular/upgrade/static
中导入了 UpgradeModule
,它导出了一些服务提供者,这些提供者会用于升级、降级服务和组件。
In the constructor of the AppModule
, use dependency injection to get a hold of the UpgradeModule
instance,
and use it to bootstrap the AngularJS app in the AppModule.ngDoBootstrap
method.
The upgrade.bootstrap
method takes the exact same arguments as angular.bootstrap:
在 AppModule
的构造函数中,使用依赖注入技术获取了一个 UpgradeModule
实例,并用它在 AppModule.ngDoBootstrap
方法中启动 AngularJS 应用。
upgrade.bootstrap
方法接受和 angular.bootstrap 完全相同的参数。
Note that you do not add a bootstrap
declaration to the @NgModule
decorator, since
AngularJS will own the root template of the application.
注意,你不需要在 @NgModule
中加入 bootstrap
声明,因为 AngularJS 控制着该应用的根模板。
Now you can bootstrap AppModule
using the platformBrowserDynamic.bootstrapModule
method.
现在,你就可以使用 platformBrowserDynamic.bootstrapModule
方法来启动 AppModule
了。
Congratulations! You're running a hybrid application! The existing AngularJS code works as before and you're ready to start adding Angular code.
恭喜!你就要开始运行这个混合式应用了!所有现存的 AngularJS 代码会像以前一样正常工作,但是你现在也同样可以运行 Angular 代码了。
Using Angular Components from AngularJS Code
在 AngularJS 的代码中使用 Angular 的组件

Once you're running a hybrid app, you can start the gradual process of upgrading code. One of the more common patterns for doing that is to use an Angular component in an AngularJS context. This could be a completely new component or one that was previously AngularJS but has been rewritten for Angular.
一旦你开始运行混合式应用,你就可以开始逐渐升级代码了。一种更常见的工作模式就是在 AngularJS 的上下文中使用 Angular 的组件。 该组件可能是全新的,也可能是把原本 AngularJS 的组件用 Angular 重写而成的。
Say you have a simple Angular component that shows information about a hero:
假设你有一个简单的用来显示英雄信息的 Angular 组件:
If you want to use this component from AngularJS, you need to downgrade it
using the downgradeComponent()
method. The result is an AngularJS
directive, which you can then register in the AngularJS module:
如果你想在 AngularJS 中使用这个组件,就得用 downgradeComponent()
方法把它降级。
其结果是一个 AngularJS 的指令,你可以把它注册到 AngularJS 的模块中:
Because HeroDetailComponent
is an Angular component, you must also add it to the
declarations
in the AppModule
.
由于 HeroDetailComponent
是一个 Angular 组件,所以你必须同时把它加入 AppModule
的 declarations
字段中。
And because this component is being used from the AngularJS module, and is an entry point into
the Angular application, you must add it to the entryComponents
for the
NgModule.
并且由于这个组件在 AngularJS 模块中使用,也是你 Angular 应用的一个入口点,你还需要
将它加入到 NgModule 的 entryComponents
列表中。
All Angular components, directives and pipes must be declared in an NgModule.
所有 Angular 组件、指令和管道都必须声明在 NgModule 中。
The net result is an AngularJS directive called heroDetail
, that you can
use like any other directive in AngularJS templates.
最终的结果是一个叫做 heroDetail
的 AngularJS 指令,你可以像用其它指令一样把它用在 AngularJS 模板中。
Note that this AngularJS is an element directive (restrict: 'E'
) called heroDetail
.
An AngularJS element directive is matched based on its name.
The selector
metadata of the downgraded Angular component is ignored.
注意,它在 AngularJS 中是一个名叫 heroDetail
的元素型指令(restrict: 'E'
)。
AngularJS 的元素型指令是基于它的名字匹配的。
Angular 组件中的 selector
元数据,在降级后的版本中会被忽略。
Most components are not quite this simple, of course. Many of them have inputs and outputs that connect them to the outside world. An Angular hero detail component with inputs and outputs might look like this:
当然,大多数组件都不像这个这么简单。它们中很多都有输入属性和输出属性,来把它们连接到外部世界。 Angular 的英雄详情组件带有像这样的输入属性与输出属性:
These inputs and outputs can be supplied from the AngularJS template, and the
downgradeComponent()
method takes care of wiring them up:
这些输入属性和输出属性的值来自于 AngularJS 的模板,而 downgradeComponent()
方法负责桥接它们:
Note that even though you are in an AngularJS template, you're using Angular attribute syntax to bind the inputs and outputs. This is a requirement for downgraded components. The expressions themselves are still regular AngularJS expressions.
注意,虽然你正在 AngularJS 的模板中,但却在使用 Angular 的属性(Attribute)语法来绑定到输入属性与输出属性。 这是降级的组件本身要求的。而表达式本身仍然是标准的 AngularJS 表达式。
There's one notable exception to the rule of using Angular attribute syntax for downgraded components. It has to do with input or output names that consist of multiple words. In Angular, you would bind these attributes using camelCase:
为降级过的组件使用 Angular 的属性(Attribute)语法规则时有一个值得注意的例外。 它适用于由多个单词组成的输入或输出属性。在 Angular 中,你要使用小驼峰命名法绑定这些属性:
[myHero]="hero" (heroDeleted)="handleHeroDeleted($event)"But when using them from AngularJS templates, you must use kebab-case:
但是从 AngularJS 的模板中使用它们时,你得使用中线命名法:
[my-hero]="hero" (hero-deleted)="handleHeroDeleted($event)"The $event
variable can be used in outputs to gain access to the
object that was emitted. In this case it will be the Hero
object, because
that is what was passed to this.deleted.emit()
.
$event
变量能被用在输出属性里,以访问这个事件所发出的对象。这个案例中它是 Hero
对象,因为 this.deleted.emit()
函数曾把它传了出来。
Since this is an AngularJS template, you can still use other AngularJS
directives on the element, even though it has Angular binding attributes on it.
For example, you can easily make multiple copies of the component using ng-repeat
:
由于这是一个 AngularJS 模板,虽然它已经有了 Angular 中绑定的属性(Attribute),你仍可以在这个元素上使用其它 AngularJS 指令。
例如,你可以用 ng-repeat
简单的制作该组件的多份拷贝:
Using AngularJS Component Directives from Angular Code
从 Angular 代码中使用 AngularJS 组件型指令

So, you can write an Angular component and then use it from AngularJS
code. This is useful when you start to migrate from lower-level
components and work your way up. But in some cases it is more convenient
to do things in the opposite order: To start with higher-level components
and work your way down. This too can be done using the upgrade/static
.
You can upgrade AngularJS component directives and then use them from
Angular.
现在,你已经能在 Angular 中写一个组件,并把它用于 AngularJS 代码中了。
当你从低级组件开始移植,并往上走时,这非常有用。但在另外一些情况下,从相反的方向进行移植会更加方便:
从高级组件开始,然后往下走。这也同样能用 UpgradeModule
完成。
你可以升级AngularJS 组件型指令,然后从 Angular 中用它们。
Not all kinds of AngularJS directives can be upgraded. The directive really has to be a component directive, with the characteristics described in the preparation guide above. The safest bet for ensuring compatibility is using the component API introduced in AngularJS 1.5.
不是所有种类的 AngularJS 指令都能升级。该指令必须是一个严格的组件型指令,具有上面的准备指南中描述的那些特征。 确保兼容性的最安全的方式是 AngularJS 1.5 中引入的组件 API。
A simple example of an upgradable component is one that just has a template and a controller:
可升级组件的简单例子是只有一个模板和一个控制器的指令:
You can upgrade this component to Angular using the UpgradeComponent
class.
By creating a new Angular directive that extends UpgradeComponent
and doing a super
call
inside its constructor, you have a fully upgraded AngularJS component to be used inside Angular.
All that is left is to add it to AppModule
's declarations
array.
你可以使用 UpgradeComponent
方法来把这个组件升级到 Angular。
具体方法是创建一个 Angular指令,继承 UpgradeComponent
,在其构造函数中进行 super
调用,
这样你就得到一个完全升级的 AngularJS 组件,并且可以 Angular 中使用。
剩下是工作就是把它加入到 AppModule
的 declarations
数组。
Upgraded components are Angular directives, instead of components, because Angular is unaware that AngularJS will create elements under it. As far as Angular knows, the upgraded component is just a directive - a tag - and Angular doesn't have to concern itself with its children.
升级后的组件是 Angular 的指令,而不是组件,因为 Angular 不知道 AngularJS 将在它下面创建元素。 Angular 所知道的是升级后的组件只是一个指令(一个标签),Angular 不需要关心组件本身及其子元素。
An upgraded component may also have inputs and outputs, as defined by the scope/controller bindings of the original AngularJS component directive. When you use the component from an Angular template, provide the inputs and outputs using Angular template syntax, observing the following rules:
升级后的组件也可能有输入属性和输出属性,它们是在原 AngularJS 组件型指令的 scope/controller 绑定中定义的。 当你从 Angular 模板中使用该组件时,就要使用Angular 模板语法来提供这些输入属性和输出属性,但要遵循下列规则:
<th>
</th>
<th>
Binding definition
绑定定义
</th>
<th>
Template syntax
模板语法
</th>
<th>
Attribute binding
属性(Attribute)绑定
</th>
<td>
`myAttribute: '@myAttribute'`
</td>
<td>
`<my-component myAttribute="value">`
</td>
<th>
Expression binding
表达式绑定
</th>
<td>
`myOutput: '&myOutput'`
</td>
<td>
`<my-component (myOutput)="action()">`
</td>
<th>
One-way binding
单向绑定
</th>
<td>
`myValue: '<myValue'`
</td>
<td>
`<my-component [myValue]="anExpression">`
</td>
<th>
Two-way binding
双向绑定
</th>
<td>
`myValue: '=myValue'`
</td>
<td>
As a two-way binding: `<my-component [(myValue)]="anExpression">`.
Since most AngularJS two-way bindings actually only need a one-way binding in practice, `<my-component [myValue]="anExpression">` is often enough.
用作双向绑定:`<my-component [(myValue)]="anExpression">`。
由于大多数 AngularJS 的双向绑定实际上只是单向绑定,因此通常写成 `<my-component [myValue]="anExpression">` 也够用了。
</td>
For example, imagine a hero detail AngularJS component directive with one input and one output:
举个例子,假设 AngularJS 中有一个表示“英雄详情”的组件型指令,它带有一个输入属性和一个输出属性:
You can upgrade this component to Angular, annotate inputs and outputs in the upgrade directive, and then provide the input and output using Angular template syntax:
你可以把这个组件升级到 Angular,然后使用 Angular 的模板语法提供这个输入属性和输出属性:
Projecting AngularJS Content into Angular Components
把 AngularJS 的内容投影到 Angular 组件中

When you are using a downgraded Angular component from an AngularJS
template, the need may arise to transclude some content into it. This
is also possible. While there is no such thing as transclusion in Angular,
there is a very similar concept called content projection. upgrade/static
is able to make these two features interoperate.
如果你在 AngularJS 模板中使用降级后的 Angular 组件时,可能会需要把模板中的一些内容投影进那个组件。
这也是可能的,虽然在 Angular 中并没有透传(transclude)这样的东西,但它有一个非常相似的概念,叫做内容投影。
UpgradeModule
也能让这两个特性实现互操作。
Angular components that support content projection make use of an <ng-content>
tag within them. Here's an example of such a component:
Angular 的组件通过使用 <ng-content>
标签来支持内容投影。下面是这类组件的一个例子:
When using the component from AngularJS, you can supply contents for it. Just
like they would be transcluded in AngularJS, they get projected to the location
of the <ng-content>
tag in Angular:
当从 AngularJS 中使用该组件时,你可以为它提供内容。正如它们将在 AngularJS 中被透传一样,
它们也在 Angular 中被投影到了 <ng-content>
标签所在的位置:
When AngularJS content gets projected inside an Angular component, it still remains in "AngularJS land" and is managed by the AngularJS framework.
当 AngularJS 的内容被投影到 Angular 组件中时,它仍然留在“AngularJS 王国”中,并被 AngularJS 框架管理着。
Transcluding Angular Content into AngularJS Component Directives
把 Angular 的内容透传进 AngularJS 的组件型指令

Just as you can project AngularJS content into Angular components, you can transclude Angular content into AngularJS components, whenever you are using upgraded versions from them.
就像可以把 AngularJS 的内容投影进 Angular 组件一样,你也能把 Angular 的内容透传进 AngularJS 的组件, 但不管怎样,你都要使用它们升级过的版本。
When an AngularJS component directive supports transclusion, it may use
the ng-transclude
directive in its template to mark the transclusion
point:
如果一个 AngularJS 组件型指令支持透传,它就会在自己的模板中使用 ng-transclude
指令标记出透传到的位置:
If you upgrade this component and use it from Angular, you can populate the component tag with contents that will then get transcluded:
如果你升级这个组件,并把它用在 Angular 中,你就能把准备透传的内容放进这个组件的标签中。
Making AngularJS Dependencies Injectable to Angular
让 AngularJS 中的依赖可被注入到 Angular
When running a hybrid app, you may encounter situations where you need to inject
some AngularJS dependencies into your Angular code.
Maybe you have some business logic still in AngularJS services.
Maybe you want access to AngularJS's built-in services like $location
or $timeout
.
当运行一个混合式应用时,可能会遇到这种情况:你需要把某些 AngularJS 的依赖注入到 Angular 代码中。
这可能是因为某些业务逻辑仍然在 AngularJS 服务中,或者需要某些 AngularJS 的内置服务,比如 $location
或 $timeout
。
In these situations, it is possible to upgrade an AngularJS provider to
Angular. This makes it possible to then inject it somewhere in Angular
code. For example, you might have a service called HeroesService
in AngularJS:
在这些情况下,把一个 AngularJS 提供者升级到Angular 也是有可能的。这就让它将来有可能被注入到 Angular 代码中的某些地方。
比如,你可能在 AngularJS 中有一个名叫 HeroesService
的服务:
You can upgrade the service using a Angular factory provider
that requests the service from the AngularJS $injector
.
你可以用 Angular 的工厂提供者升级该服务,
它从 AngularJS 的 $injector
请求服务。
Many developers prefer to declare the factory provider in a separate ajs-upgraded-providers.ts
file
so that they are all together, making it easier to reference them, create new ones and
delete them once the upgrade is over.
很多开发者都喜欢在一个独立的 ajs-upgraded-providers.ts
中声明这个工厂提供者,以便把它们都放在一起,这样便于引用、创建新的以及在升级完毕时删除它们。
It's also recommended to export the heroesServiceFactory
function so that Ahead-of-Time
compilation can pick it up.
同时,建议导出 heroesServiceFactory
函数,以便 AOT 编译器可以拿到它们。
Note: The 'heroes' string inside the factory refers to the AngularJS HeroesService
.
It is common in AngularJS apps to choose a service name for the token, for example "heroes",
and append the "Service" suffix to create the class name.
**注意:**这个工厂中的字符串 'heroes' 指向的是 AngularJS 的 HeroesService
。
AngularJS 应用中通常使用服务名作为令牌,比如 'heroes',并为其追加 'Service' 后缀来创建其类名。
You can then provide the service to Angular by adding it to the @NgModule
:
然后,你就可以把这个服务添加到 @NgModule
中来把它暴露给 Angular:
Then use the service inside your component by injecting it in the component constructor using its class as a type annotation:
然后在组件的构造函数中使用该服务的类名作为类型注解注入到组件中,从而在组件中使用它:
In this example you upgraded a service class. You can use a TypeScript type annotation when you inject it. While it doesn't affect how the dependency is handled, it enables the benefits of static type checking. This is not required though, and any AngularJS service, factory, or provider can be upgraded.
在这个例子中,你升级了服务类。当注入它时,你可以使用 TypeScript 类型注解来获得这些额外的好处。 它没有影响该依赖的处理过程,同时还得到了启用静态类型检查的好处。 任何 AngularJS 中的服务、工厂和提供者都能被升级 —— 尽管这不是必须的。
Making Angular Dependencies Injectable to AngularJS
让 Angular 的依赖能被注入到 AngularJS 中
In addition to upgrading AngularJS dependencies, you can also downgrade Angular dependencies, so that you can use them from AngularJS. This can be useful when you start migrating services to Angular or creating new services in Angular while retaining components written in AngularJS.
除了能升级 AngularJS 依赖之外,你还能降级Angular 的依赖,以便在 AngularJS 中使用它们。 当你已经开始把服务移植到 Angular 或在 Angular 中创建新服务,但同时还有一些用 AngularJS 写成的组件时,这会非常有用。
For example, you might have an Angular service called Heroes
:
例如,你可能有一个 Angular 的 Heroes
服务:
Again, as with Angular components, register the provider with the NgModule
by adding it to the module's providers
list.
仿照 Angular 组件,把该提供者加入 NgModule
的 providers
列表中,以注册它。
Now wrap the Angular Heroes
in an AngularJS factory function using downgradeInjectable()
and plug the factory into an AngularJS module.
The name of the AngularJS dependency is up to you:
现在,用 downgradeInjectable()
来把 Angular 的 Heroes
包装成AngularJS 的工厂函数,并把这个工厂注册进 AngularJS 的模块中。
依赖在 AngularJS 中的名字你可以自己定:
After this, the service is injectable anywhere in AngularJS code:
此后,该服务就能被注入到 AngularJS 代码中的任何地方了:
Lazy Loading AngularJS
惰性加载 AngularJS
When building applications, you want to ensure that only the required resources are loaded when necessary. Whether that be loading of assets or code, making sure everything that can be deferred until needed keeps your application running efficiently. This is especially true when running different frameworks in the same application.
在构建应用时,你需要确保只在必要的时候才加载所需的资源,无论是加载静态资产(Asset)还是代码。要确保任何事都尽量推迟到必要时才去做,以便让应用更高效的运行。当要在同一个应用中运行不同的框架时,更是如此。
Lazy loading is a technique that defers the loading of required assets and code resources until they are actually used. This reduces startup time and increases efficiency, especially when running different frameworks in the same application.
惰性加载是一项技术,它会推迟到使用时才加载所需静态资产和代码资源。这可以减少启动时间、提高效率,特别是要在同一个应用中运行不同的框架时。
When migrating large applications from AngularJS to Angular using a hybrid approach, you want to migrate some of the most commonly used features first, and only use the less commonly used features if needed. Doing so helps you ensure that the application is still providing a seamless experience for your users while you are migrating.
当你采用混合式应用的方式将大型应用从 AngularJS 迁移到 Angular 时,你首先要迁移一些最常用的特性,并且只在必要的时候才使用那些不太常用的特性。这样做有助于确保应用程序在迁移过程中仍然能为用户提供无缝的体验。
In most environments where both Angular and AngularJS are used to render the application, both frameworks are loaded in the initial bundle being sent to the client. This results in both increased bundle size and possible reduced performance.
在大多数需要同时用 Angular 和 AngularJS 渲染应用的环境中,这两个框架都会包含在发送给客户端的初始发布包中。这会导致发布包的体积增大、性能降低。
Overall application performance is affected in cases where the user stays on Angular-rendered pages because the AngularJS framework and application are still loaded and running, even if they are never accessed.
当用户停留在由 Angular 渲染的页面上时,应用的整体性能也会受到影响。这是因为 AngularJS 的框架和应用仍然被加载并运行了 —— 即使它们从未被访问过。
You can take steps to mitigate both bundle size and performance issues. By isolating your AngularJS app to a separate bundle, you can take advantage of lazy loading to load, bootstrap, and render the AngularJS application only when needed. This strategy reduces your initial bundle size, defers any potential impact from loading both frameworks until absolutely necessary, and keeps your application running as efficiently as possible.
你可以采取一些措施来缓解这些包的大小和性能问题。通过把 AngularJS 应用程序分离到一个单独的发布包中,你就可以利用惰性加载技术来只在必要的时候才加载、引导和渲染这个 AngularJS 应用。这种策略减少了你的初始发布包大小,推迟了同时加载两个框架的潜在影响 —— 直到绝对必要时才加载,以便让你的应用尽可能高效地运行。
The steps below show you how to do the following:
下面的步骤介绍了应该如何去做:
-
Setup a callback function for your AngularJS bundle.
为 AngularJS 发布包设置一个回调函数。
-
Create a service that lazy loads and bootstraps your AngularJS app.
创建一个服务,以便惰性加载并引导你的 AngularJS 应用。
-
Create a routable component for AngularJS content
为 AngularJS 的内容创建一个可路由的组件
-
Create a custom
matcher
function for AngularJS-specific URLs and configure the AngularRouter
with the custom matcher for AngularJS routes.为 AngularJS 特有的 URL 创建自定义的
matcher
函数,并为 AngularJS 的各个路由配上带有自定义匹配器的 Angular 路由器。
Create a service to lazy load AngularJS
为惰性加载 AngularJS 创建一个服务
As of Angular version 8, lazy loading code can be accomplished simply by using the dynamic import syntax import('...')
. In your application, you create a new service that uses dynamic imports to lazy load AngularJS.
在 Angular 的版本 8 中,惰性加载代码只需使用动态导入语法 import('...')
即可。在这个应用中,你创建了一个新服务,它使用动态导入技术来惰性加载 AngularJS。
The service uses the import()
method to load your bundled AngularJS application lazily. This decreases the initial bundle size of your application as you're not loading code your user doesn't need yet. You also need to provide a way to bootstrap the application manually after it has been loaded. AngularJS provides a way to manually bootstrap an application using the angular.bootstrap() method with a provided HTML element. Your AngularJS app should also expose a bootstrap
method that bootstraps the AngularJS app.
该服务使用 import()
方法惰性加载打包好的 AngularJS 应用。这会减少应用初始包的大小,因为你尚未加载用户目前不需要的代码。你还要提供一种方法,在加载完毕后手动启动它。AngularJS 提供了一种使用 angular.bootstrap() 方法并传入一个 HTML 元素来手动引导应用的方法。你的 AngularJS 应用也应该公开一个用来引导 AngularJS 应用的 bootstrap
方法。
To ensure any necessary teardown is triggered in the AngularJS app, such as removal of global listeners, you also implement a method to call the $rootScope.destroy()
method.
要确保 AngularJS 应用中的任何清理工作都触发过(比如移除全局监听器),你还可以实现一个方法来调用 $rootScope.destroy()
方法。
Your AngularJS application is configured with only the routes it needs to render content. The remaining routes in your application are handled by the Angular Router. The exposed bootstrap
method is called in your Angular app to bootstrap the AngularJS application after the bundle is loaded.
你的 AngularJS 应用只配置了渲染内容所需的那部分路由。而 Angular 路由器会处理应用中其余的路由。你的 Angular 应用中会调用公开的 bootstrap
方法,让它在加载完发布包之后引导 AngularJS 应用。
Note: After AngularJS is loaded and bootstrapped, listeners such as those wired up in your route configuration will continue to listen for route changes. To ensure listeners are shut down when AngularJS isn't being displayed, configure an otherwise
option with the $routeProvider that renders an empty template. This assumes all other routes will be handled by Angular.
**注意:**当 AngularJS 加载并引导完毕后,监听器(比如路由配置中的那些监听器)会继续监听路由的变化。为了确保当 AngularJS 尚未显示时先关闭监听器,请在 $routeProvider 中配置一个渲染空模板 otherwise
选项。这里假设 Angular 将处理所有其它路由。
Create a component to render AngularJS content
创建一个用来渲染 AngularJS 内容的组件
In your Angular application, you need a component as a placeholder for your AngularJS content. This component uses the service you create to load and bootstrap your AngularJS app after the component is initialized.
在 Angular 应用中,你需要一个组件作为 AngularJS 内容的占位符。该组件使用你创建的服务,并在组件初始化完成后加载并引导你的 AngularJS 应用。
When the Angular Router matches a route that uses AngularJS, the AngularJSComponent
is rendered, and the content is rendered within the AngularJS ng-view
directive. When the user navigates away from the route, the $rootScope
is destroyed on the AngularJS application.
当 Angular 的路由器匹配到使用 AngularJS 的路由时,会渲染 AngularJSComponent
,并在 AngularJS 的 ng-view
指令中渲染内容。当用户导航离开本路由时,$rootScope
会在 AngularJS 应用中被销毁。
Configure a custom route matcher for AngularJS routes
为那些 AngularJS 路由配置自定义路由匹配器
To configure the Angular Router, you must define a route for AngularJS URLs. To match those URLs, you add a route configuration that uses the matcher
property. The matcher
allows you to use custom pattern matching for URL paths. The Angular Router tries to match on more specific routes such as static and variable routes first. When it doesn't find a match, it then looks at custom matchers defined in your route configuration. If the custom matchers don't match a route, it then goes to catch-all routes, such as a 404 page.
为了配置 Angular 的路由器,你必须为 AngularJS 的 URL 定义路由。要匹配这些 URL,你需要添加一个使用 matcher
属性的路由配置。这个 matcher
允许你使用自定义模式来匹配这些 URL 路径。Angular 的路由器会首先尝试匹配更具体的路由,比如静态路由和可变路由。当它找不到匹配项时,就会求助于路由配置中的自定义匹配器。如果自定义匹配器与某个路由不匹配,它就会转到用于 "捕获所有"(catch-all)的路由,比如 404 页面。
The following example defines a custom matcher function for AngularJS routes.
下面的例子给 AngularJS 路由定义了一个自定义匹配器函数。
The following code adds a route object to your routing configuration using the matcher
property and custom matcher, and the component
property with AngularJSComponent
.
下列代码往你的路由配置中添加了一个路由对象,其 matcher
属性是这个自定义匹配器,而 component
属性为 AngularJSComponent
。
When your application matches a route that needs AngularJS, the AngularJS app is loaded and bootstrapped, the AngularJS routes match the necessary URL to render their content, and your application continues to run with both AngularJS and Angular frameworks.
当你的应用匹配上需要 AngularJS 的路由时,AngularJS 应用就会被加载并引导。AngularJS 路由会匹配必要的 URL 以渲染它们的内容,而接下来你的应用就会同时运行 AngularJS 和 Angular 框架。
Using the Unified Angular Location Service
使用统一的 Angular 位置服务(Location)
In AngularJS, the $location service handles all routing configuration and navigation, encoding and decoding of URLS, redirects, and interactions with browser APIs. Angular uses its own underlying Location
service for all of these tasks.
在 AngularJS 中,$location 服务会处理所有路由配置和导航工作,并对各个 URL 进行编码和解码、重定向、以及与浏览器 API 交互。Angular 在所有这些任务中都使用了自己的底层服务 Location
。
When you migrate from AngularJS to Angular you will want to move as much responsibility as possible to Angular, so that you can take advantage of new APIs. To help with the transition, Angular provides the LocationUpgradeModule
. This module enables a unified location service that shifts responsibilities from the AngularJS $location
service to the Angular Location
service.
当你从 AngularJS 迁移到 Angular 时,你会希望把尽可能多的责任移交给 Angular,以便利用新的 API。为了帮你完成这种转换,Angular 提供了 LocationUpgradeModule
。该模块支持统一位置服务,可以把 AngularJS 中 $location
服务的职责转给 Angular 的 Location
服务。
To use the LocationUpgradeModule
, import the symbol from @angular/common/upgrade
and add it to your AppModule
imports using the static LocationUpgradeModule.config()
method.
要使用 LocationUpgradeModule
,就会从 @angular/common/upgrade
中导入此符号,并使用静态方法 LocationUpgradeModule.config()
把它添加到你的 AppModule
导入表(imports
)中。
// Other imports ...
import { LocationUpgradeModule } from '@angular/common/upgrade';
@NgModule({
imports: [
// Other NgModule imports...
LocationUpgradeModule.config()
]
})
export class AppModule {}
The LocationUpgradeModule.config()
method accepts a configuration object that allows you to configure options including the LocationStrategy
with the useHash
property, and the URL prefix with the hashPrefix
property.
LocationUpgradeModule.config()
方法接受一个配置对象,该对象的 useHash
为 LocationStrategy
,hashPrefix
为 URL 前缀。
The useHash
property defaults to false
, and the hashPrefix
defaults to an empty string
. Pass the configuration object to override the defaults.
useHash
属性默认为 false
,而 hashPrefix
默认为空 string
。传递配置对象可以覆盖默认值。
LocationUpgradeModule.config({
useHash: true,
hashPrefix: '!'
})
Note: See the LocationUpgradeConfig
for more configuration options available to the LocationUpgradeModule.config()
method.
**注意:**有关 LocationUpgradeModule.config()
方法的更多可用配置项,请参阅 LocationUpgradeConfig
。
This registers a drop-in replacement for the $location
provider in AngularJS. Once registered, all navigation, routing broadcast messages, and any necessary digest cycles in AngularJS triggered during navigation are handled by Angular. This gives you a single way to navigate within both sides of your hybrid application consistently.
这会为 AngularJS 中的 $location
提供者注册一个替代品。一旦注册成功,导航过程中所有由 AngularJS 触发的导航、路由广播消息以及任何必需的变更检测周期都会改由 Angular 进行处理。这样,你就可以通过这个唯一的途径在此混合应用的两个框架间进行导航了。
For usage of the $location
service as a provider in AngularJS, you need to downgrade the $locationShim
using a factory provider.
要想在 AngularJS 中使用 $location
服务作为提供者,你需要使用一个工厂提供者来降级 $locationShim
。
// Other imports ...
import { $locationShim } from '@angular/common/upgrade';
import { downgradeInjectable } from '@angular/upgrade/static';
angular.module('myHybridApp', [...])
.factory('$location', downgradeInjectable($locationShim));
Once you introduce the Angular Router, using the Angular Router triggers navigations through the unified location service, still providing a single source for navigating with AngularJS and Angular.
一旦引入了 Angular 路由器,你只要使用 Angular 路由器就可以通过统一位置服务来触发导航了,同时,你仍然可以通过 AngularJS 和 Angular 进行导航。