angular-cn/public/docs/ts/latest/guide/upgrade.jade

2592 lines
136 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

include ../_util-fns
:marked
Having an existing Angular 1 application doesn't mean that we can't
begin enjoying everything Angular 2 has to offer. That's because Angular 2
comes with built-in tools for migrating Angular 1 projects over to the
Angular 2 platform.
已经有了一个Angular 1的程序并不表示我们就不能享受Angular 2提供的一切。
这是因为Angular 2带来了一些内置工具来帮助我们把Angular 1的项目迁移到Angular 2平台。
Some applications will be easier to upgrade than others, and there are
ways in which we can make it easier for ourselves. It is possible to
prepare and align Angular 1 applications with Angular 2 even before beginning
the upgrade process. These preparation steps are all about making the code
more decoupled, more maintainable, and up to speed with modern development
tools. That means the preparation work will not only make the eventual upgrade
easier, but will also generally improve our Angular 1 applications.
有些应用可能比其它的升级起来简单,还有一些方法能让把这项工作变得更简单。
即使在正式开始升级过程之前我们可以准备Angular 1的程序让它向Angular 2看齐。
这些准备步骤几乎都是关于如何让代码更加松耦合、更有可维护性,以及用现代开发工具提高速度的。
这意味着这种准备工作不仅能让最终的升级变得更简单而且还能提升Angular 1程序的质量。
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 Angular 1 components to Angular 2 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 2 has been designed to
make incremental upgrading seamless.
成功升级的关键之一是增量式的实现它通过在同一个应用中一起运行这两个框架并且逐个把Angular 1的组件迁移到Angular 2中。
这意味着可以在不必打断其它业务的前提下,升级更大、更复杂的应用程序,因为这项工作可以多人协作完成,在一段时间内逐渐铺开。
Angular 2 `upgrade`模块的设计目标就是让你渐进、无缝的完成升级。
1. [Preparation](#preparation)
1. [准备工作](#preparation)
1. [Follow the Angular Style Guide](#follow-the-angular-style-guide)
1. [遵循Angular风格指南](#follow-the-angular-style-guide)
2. [Using a Module Loader](#using-a-module-loader)
2. [使用模块加载器](#using-a-module-loader)
3. [Migrating to TypeScript](#migrating-to-typescript)
3. [迁移到TypeScript](#migrating-to-typescript)
4. [Using Component Directives](#using-component-directives)
4. [使用组件型指令](#using-component-directives)
2. [Upgrading with The Upgrade Module](#upgrading-with-the-upgrade-module)
2. [通过升级模块进行升级](#upgrading-with-the-upgrade-module)
1. [How The Upgrade Module Works](#how-the-upgrade-module-works)
1. [升级模块是如何工作的](#how-the-upgrade-module-works)
2. [Bootstrapping hybrid Angular 1+2 Applications](#bootstrapping-hybrid-angular-1-2-applications)
2. [引导Angular 1和2的混合(hybrid)应用](#bootstrapping-hybrid-angular-1-2-applications)
3. [Using Angular 2 Components from Angular 1 Code](#using-angular-2-components-from-angular-1-code)
3. [从Angular 1的代码中使用Angular 2的组件](#using-angular-2-components-from-angular-1-code)
4. [Using Angular 1 Component Directives from Angular 2 Code](#using-angular-1-component-directives-from-angular-2-code)
4. [从Angular 2的代码中使用Angular 1的组件](#using-angular-1-component-directives-from-angular-2-code)
5. [Projecting Angular 1 Content into Angular 2 Components](#projecting-angular-1-content-into-angular-2-components)
5. [把Angular 1的内容投影(project)进Angular 2组件中](#projecting-angular-1-content-into-angular-2-components)
6. [Transcluding Angular 2 Content into Angular 1 Component Directives](#transcluding-angular-2-content-into-angular-1-component-directives)
6. [把Angular 2的内容透传(transclude)到Angular 1的组件型指令中](#transcluding-angular-2-content-into-angular-1-component-directives)
7. [Making Angular 1 Dependencies Injectable to Angular 2](#making-angular-1-dependencies-injectable-to-angular-2)
7. [让Angular 1提供的依赖可以被注入到Angular 2](#making-angular-1-dependencies-injectable-to-angular-2)
8. [Making Angular 2 Dependencies Injectable to Angular 1](#making-angular-2-dependencies-injectable-to-angular-1)
8. [让Angular 2提供的依赖可以被注入到Angular 1](#making-angular-2-dependencies-injectable-to-angular-1)
3. [PhoneCat Upgrade Tutorial](#phonecat-upgrade-tutorial)
3. [PhoneCat准备工作教程](#phonecat-preparation-tutorial)
1. [Switching to TypeScript](#switching-to-typescript)
1. [切换到TypeScript](#switching-to-typescript)
2. [Installing Angular 2](#installing-angular-2)
2. [安装Angular 2](#installing-angular-2)
3. [Bootstrapping a hybrid 1+2 PhoneCat](#bootstrapping-a-hybrid-1-2-phonecat)
3. [引导Angular 1+2的混合版PhoneCat](#bootstrapping-a-hybrid-1-2-phonecat)
4. [Upgrading the Phone service](#upgrading-the-phone-service)
4. [升级Phone服务](#upgrading-the-phone-service)
5. [Upgrading Components](#upgrading-components)
5. [升级组件](#upgrading-components)
6. [Switching To The Angular 2 Router And Bootstrap](#switching-to-the-angular-2-router-and-bootstrap)
6. [切换到Angular 2的路由器并引导](#switching-to-the-angular-2-router-and-bootstrap)
7. [Saying Goodbye to Angular 1](#saying-goodbye-to-angular-1)
3. [Appendix: Upgrading PhoneCat Tests](#appendix-upgrading-phonecat-tests)
3. [附录升级PhoneCat测试](#appendix-upgrading-phonecat-tests)
.l-main-section
:marked
## Preparation
## 准备工作
There are many ways to structure Angular 1 applications. When we begin
to upgrade these applications to Angular 2, some will turn out to be
much more easy to work with than others. There are a few key techniques
and patterns that we can apply to future proof our apps even before we
begin the migration.
Angular 1应用程序的组织方式有很多种。当我们想把它们升级到Angular 2的时候
有些做起来会比其它的更容易些。即使在我们开始升级之前,也有一些关键的技术和模式可以让我们将来升级时更轻松。
### Follow the Angular Style Guide
### 遵循Angular风格指南
The [Angular 1 Style Guide](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility)
collects patterns and practices that have been proven to result in
cleaner and more maintainable Angular 1 applications. It contains a wealth
of information about how to write and organize Angular code - and equally
importantly - how **not** to write and organize Angular code.
[Angular风格指南](https://github.com/johnpapa/angular-styleguide)收集了一些已证明能写出干净且可维护的Angular 1程序的模式与实践。
它包含了很多关于如何书写和组织Angular代码的有价值信息同样重要的是**不应该**采用的书写和组织Angular代码的方式。
Angular 2 is a reimagined version of the best parts of Angular 1. In that
sense, its goals are the same as the Angular Style Guide's: To preserve
the good parts of Angular 1, and to avoid the bad parts. There's a lot
more to Angular 2 than just that of course, but this does mean that
*following the style guide helps make your Angular 1 app more closely
aligned with Angular 2*.
Angular 2是一个基于Angular 1中最好的部分构思出来的版本。在这种意义上它的目标和Angular风格指南是一样的
保留Angular 1中好的部分去掉坏的部分。当然Angular 2还做了更多。
说这些的意思是:*遵循这个风格指南可以让你写出更接近Angular 2程序的Angular 1程序*。
There are a few rules in particular that will make it much easier to do
*an incremental upgrade* using the Angular 2 `upgrade` module:
特别是某些规则会让使用Angular 2的`upgrade`模块进行*增量升级*变得更简单:
* The [Rule of 1](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility)
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.
* [单一规则](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility)
规定每个文件应该只放一个组件。这不仅让组件更容易浏览和查找,而且还将允许我们逐个迁移它们的语言和框架。
在这个范例程序中,每个控制器、工厂和过滤器都在它自己的源文件中。
* The [Folders-by-Feature Structure](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#folders-by-feature-structure)
and [Modularity](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#modularity)
rules define similar principles on a higher level of abstraction: Different parts of the
application should reside in different directories and Angular modules.
* [按特性分目录的结构](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#folders-by-feature-structure)和[模块化](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#modularity)规则在较高的抽象层定义了一些相似的原则应用程序中的不同部分应该被分到不同的目录和Angular模块中。
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 Angular 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 we break application code down into one component per file, we 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](https://github.com/systemjs/systemjs),
[Webpack](http://webpack.github.io/), or [Browserify](http://browserify.org/)
allows us to use the built-in module systems of the TypeScript or ES2015 languages in our apps.
We 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
we 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](https://github.com/systemjs/systemjs)、
[Webpack](http://webpack.github.io/)或[Browserify](http://browserify.org/)
可以让我们在程序中使用TypeScript或ES2015语言内置的模块系统。
我们可以使用`import`和`export`特性来明确指定哪些代码应该以及将会被在程序的不同部分之间共享。
对于ES5程序来说我们可以改用CommonJS风格的`require`和`module.exports`特性代替。
无是论哪种情况,模块加载器都会按正确的顺序加载程序中用到的所有代码。
When we then take our applications into production, module loaders also make it easier
to package them all up into production bundles with batteries included.
当我们的应用程序投入生产环境时,模块加载器也会让把所有这些文件打成完整的产品包变得更容易。
:marked
### Migrating to TypeScript
### 迁移到TypeScript
If part of our Angular 2 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 we can start using TypeScript features in our Angular 1 code.
Angular 2升级计划的一部分是引入TypeScript即使在开始升级之前引入TypeScript编译器也是有意义的。
这意味着等真正升级的时候需要学习和思考的东西更少。
它还意味着我们可以在Angular 1代码中开始使用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 switching 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 and `const`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 2 service and component classes, which will make our
life easier once we do the upgrade.
* 服务和控制器可以转成*类*。这样我们就能一步步接近Angular 2的服务和组件类了这样等到我们开始升级时也会更简单。
### Using Component Directives
### 使用组件型指令
In Angular 2, components are the main primitive from which user interfaces
are built. We define the different parts of our UIs as components, and then
compose the UI by using components in our templates.
在Angular 2中组件是用来构建用户界面的主要元素。我们把UI中的不同部分定义成组件然后通过在模板中使用这些组件最终合成为UI。
You can also do this in Angular 1, using *component directives*. These are
directives that define their own templates, controllers, and input/output bindings -
the same things that Angular 2 components define. Applications built with
component directives are much easier to migrate to Angular 2 than applications
built with lower-level features like `ng-controller`, `ng-include`, and scope
inheritance.
我们在Angular 1中也能这么做。那就是一种定义了自己的模板、控制器和输入/输出绑定的指令 —— 跟Angular 2中对组件的定义是一样的。
要迁移到Angular 2通过组件型指令构建的应用程序会比直接用`ng-controller`、`ng-include`和作用域继承等底层特性构建的要容易得多。
To be Angular 2 compatible, an Angular 1 component directive should configure
these attributes:
要与Angular 2兼容Angular 1的组件型指令应该配置下列属性
* `restrict: 'E'`. Components are usually used as elements.
* `restrict: 'E'`。组件通常会以元素的方式使用。
* `scope: {}` - an isolate scope. In Angular 2, components are always isolated
from their surroundings, and we should do this in Angular 1 too.
* `scope: {}` - 一个独立作用域。在Angular 2中组件永远是从它们的环境中被隔离出来的在Angular 1中我们也应该这么做。
* `bindToController: {}`. Component inputs and outputs should be bound
to the controller instead of using the `$scope`.
* `bindToController: {}`。组件的输入和输出应该绑定到控制器,而不是`$scope`。
* `controller` and `controllerAs`. Components have their own controllers.
* `controller`和`controllerAs`。组件有它们自己的控制器。
* `template` or `templateUrl`. 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 **may not** use the following attributes:
组件型指令**不能**使用下列属性:
* `compile`. This will not be supported in Angular 2.
* `compile`。它在Angular 2中将不再被支持。
* `replace: true`. Angular 2 never replaces a component element with the
component template. This attribute is also deprecated in Angular 1.
* `replace: true`。Angular永远不会用组件模板替换一个组件元素。这个特性在Angular 1中也同样不建议使用了。
* `priority` and `terminal`. While Angular 1 components may use these,
they are not used in Angular 2 and it is better not to write code
that relies on them.
* `priority`和`terminal`。虽然Angular 1的组件可能使用这些但它们在Angular 2中已经没用了并且最好不要再写依赖它们的代码。
An Angular 1 component directive that is fully aligned with the Angular 2
architecture may look something like this:
Angular 1中一个完全向Angular 2架构看齐过的组件型指令看起来有点像这样
+makeExample('upgrade-module/ts/app/hero-detail.directive.ts')
:marked
Angular 1.5 introduces the [component API](https://docs.angularjs.org/api/ng/type/angular.Module)
that makes it easier to define directives like these. It is a good idea to use
this API for component directives for several reasons:
Angular 1.5引入了[组件API](https://docs.angularjs.org/api/ng/type/angular.Module),它让像这样定义指令变得更简单了。
为组件型指令使用这个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` and `restrict`.
* 对于指令中像`scope`和`restrict`这样的属性,它有良好的默认值。
The component directive example from above looks like this when expressed
using the component API:
如果使用这个组件API进行快捷定义那么上面看到的组件型指令就变成了这样
+makeExample('upgrade-module/ts/app/upgrade-io/hero-detail.component.ts')
:marked
Controller lifecycle hook methods `$onInit()`, `$onDestroy()`, and `$onChanges()`
are another convenient feature that Angular 1.5 introduces. They all have nearly
exact [equivalents in Angular 2](lifecycle-hooks.html), so organizing component lifecycle
logic around them will ease the eventual Angular 2 upgrade process.
控制器的生命周期钩子`$onInit()`、`$onDestroy()`和`$onChanges()`是Angular 1.5引入的另一些便利特性。
它们都很接近于[Angular 2中的等价物](lifecycle-hooks.html),所以,围绕它们组织组件生命周期的逻辑会更容易升级。
.l-main-section
:marked
## Upgrading with The Upgrade Module
## 使用升级适配器进行升级
The `upgrade` module in Angular 2 is a very useful tool for upgrading
anything but the smallest of applications. With it we can mix and match
Angular 1 and 2 components in the same application and have them interoperate
seamlessly. That means we 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 2中的`upgrade`模块都会是一个非常有用的工具 —— 除非是小到没功能的应用。
借助它我们可以在同一个应用程序中混用并匹配Angular 1和2的组件并让它们实现无缝的互操作。
这意味着我们不用必须一次性做完所有升级工作,因为在整个演进过程中,这两个框架可以很自然的和睦相处。
### How The Upgrade Module Works
### 升级模块如何工作
The primary tool provided by the upgrade module is called the `UpgradeModule`.
This is a service that can bootstrap and manage hybrid applications that support
both Angular 2 and Angular 1 code.
`upgrade`模块提供的主要工具叫做`UpgradeModule`。这是一个服务它可以引导并管理同时支持Angular 2和Angular 1的混合式应用程序。
When we use `UpgradeModule`, what we're really doing is *running both versions
of Angular at the same time*. All Angular 2 code is running in the Angular 2
framework, and Angular 1 code in the Angular 1 framework. Both of these are the
actual, fully featured versions of the frameworks. There is no emulation going on,
so we can expect to have all the features and natural behavior of both frameworks.
当使用`UpgradeModule`时,我们实际做的是*同时运行两个版本的Angular*。所有Angular 2的代码运行在Angular 2框架中
而Angular 1的代码运行在Angular 1框架中。所有这些都是真实的、全功能的框架版本。
没有进行任何仿真,所以我们可以期待同时存在这两个框架的所有特性和天生的行为。
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 Angular 1 and
Angular 2, but there are some key differences between the two
frameworks in how it actually works.
无论是在Angular 1中还是在Angular 2中依赖注入都处于前沿和中心的位置但在两个框架的工作原理上却存在着一些关键的不同之处。
table
tr
th Angular 1
th Angular 2
tr
td
:marked
Dependency injection tokens are always strings
依赖注入的令牌(Token)永远是字符串(译注:指服务名称)。
td
:marked
Tokens [can have different types](../guide/dependency-injection.html).
They are often classes. They may also be strings.
令牌[可能有不同的类型](../guide/dependency-injection.html)。
通常是类,也可能是字符串。
tr
td
:marked
There is exactly one injector. Even in multi-module applications,
everything is poured into one big namespace.
只有一个注入器。即使在多模块的应用程序中,每样东西也都被装入一个巨大的命名空间中。
td
:marked
There is a [tree hierarchy of injectors](../guide/hierarchical-dependency-injection.html),
with a root injector and an additional injector for each component.
有一组[树状多层注入器](../guide/hierarchical-dependency-injection.html),有一个根注入器,每个组件也另外有一个注入器。
:marked
Even accounting for these differences we can still have dependency injection
interoperability. The `UpgradeModule` resolves the differences and makes
everything work seamlessly:
就算有这么多不同点,也并不妨碍我们在依赖注入时进行互操作。`UpgradeModule`解决了这些差异,并让它们无缝的对接:
* We can make Angular 1 services available for injection to Angular 2 code
by *upgrading* them. The same singleton instance of each service is shared
between the frameworks. In Angular 2 these services will always be in the
*root injector* and available to all components. They will always have
*string tokens* - the same tokens that they have in Angular 1.
* 通过升级它们我们就能让那些在Angular 1中能被注入的服务在Angular 2的代码中可用。
在框架之间共享的是服务的同一个单例对象。在Angular 2中这些外来服务总是被放在*根注入器*中,并可用于所有组件。
它们总是具有*字符串令牌* —— 跟它们在Angular 1中的令牌相同。
* We can also make Angular 2 services available for injection to Angular 1 code
by *downgrading* them. Only services from the Angular 2 root injector can
be downgraded. Again, the same singleton instances are shared between the frameworks.
When we register a downgrade, we explicitly specify a *string token* that we want to
use in Angular 1.
* 通过降级它们我们也能让那些在Angular 2中能被注入的服务在Angular 1的代码中可用。
只有那些来自Angular 2根注入器的服务才能被降级。同样的在框架之间共享的是同一个单例对象。
当我们注册一个要降级的服务时要明确指定一个打算在Angular 1中使用的*字符串令牌*。
figure.image-display
img(src="/resources/images/devguide/upgrade/injectors.png" alt="The two injectors in a hybrid application" width="700")
:marked
#### Components and the DOM
#### 组件与DOM
What we'll find in the DOM of a hybrid application are components and
directives from both Angular 1 and Angular 2. These components
communicate with each other by using the input and output bindings
of their respective frameworks, which the `UpgradeModule` bridges
together. They may also communicate through shared injected dependencies,
as described above.
在混合式应用中我们能同时发现那些来自Angular 1和Angular 2中组件和指令的DOM。
这些组件通过它们各自框架中的输入和输出绑定来互相通讯,它们由`UpgradeModule`桥接在一起。
它们也能通过共享被注入的依赖彼此通讯,就像前面所说的那样。
There are two key things to understand about what happens in the DOM
of a hybrid application:
要弄明白在一个混合式应用的DOM中发生了什么有两点很关键
1. 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 Angular 1, Angular 2 treats it as if it didn't exist,
and vice versa.
1. DOM中的每个元素都只能被两个框架之一拥有。另一个框架会忽略它。
如果一个元素被Angular 1拥有Angular 2就会当它不存在。反之亦然。
2. The root of the application *is always an Angular 1 template*.
2. 应用的根节点*总是来自Angular 1中的模板*。
So a hybrid application begins life as an Angular 1 application,
and it is Angular 1 that processes its root template. Angular 2 then steps
into the picture when an Angular 2 component is used somewhere in
the application templates. That component's view will then be managed
by Angular 2, and it may use any number of Angular 2 components and
directives.
所以混合式应用总是像Angular 1程序那样启动处理根模板的也是Angular 1.
然后当这个应用的模板中使用到了Angular 2的组件时Angular 2才开始参与。
这个组件的视图由Angular 2进行管理而且它还可以使用一系列的Angular 2组件和指令。
Beyond that, we may interleave the two frameworks as much as we need to.
We always cross the boundary between the two frameworks by one of two
ways:
更进一步说,我们可以按照需要,任意穿插使用这两个框架。
使用下面的两种方式之一,我们可以自由穿梭于这两个框架的边界:
1. By using a component from the other framework: An Angular 1 template
using an Angular 2 component, or an Angular 2 template using an
Angular 1 component.
1. 通过使用来自另一个框架的组件Angular 1的模板中用到了Angular 2的组件或者Angular 2的模板中使用了Angular 1的组件。
2. By transcluding or projecting content from the other framework. The
`UpgradeModule` bridges the related concepts of Angular 1 transclusion
and Angular 2 content projection together.
2. 通过透传(transclude)或投影(project)来自另一个框架的内容。`UpgradeModule`牵线搭桥把Angular 1的透传概念和Angular 2的内容投影概念关联起来。
figure.image-display
img(src="/resources/images/devguide/upgrade/dom.png" alt="DOM element ownership in a hybrid application" width="500")
:marked
Whenever we use a component that belongs to the other framework, a
switch between framework boundaries occurs. However, that switch only
happens to the *children* of the component element. Consider a situation
where we use an Angular 2 component from Angular 1 like this:
无论什么时候,只要我们用到了来自另一个框架的组件,就会发生框架边界的切换。然而,这种切换只会发生在组件元素的*子节点*上。
考虑一个场景我们从Angular 1中像这样使用Angular 2的组件
```
<ng2-component></ng2-component>
```
The DOM element `<ng2-component>` will remain to be an Angular 1 managed
element, because it's defined in an Angular 1 template. That also
means you can apply additional Angular 1 directives to it, but *not*
Angular 2 directives. It is only in the template of the `Ng2Component`
component where Angular 2 steps in. This same rule also applies when you
use Angular 1 component directives from Angular 2.
此时,`<ng2-component>`这个DOM元素仍然由Angular 1管理因为它是在Angular 1的模板中定义的。
这也意味着你可以往它上面添加别的Angular 1指令却*不能*添加Angular 2的指令。
只有在`Ng2Component`组件的模板中才是Angular 2的天下。同样的规则也适用于在Angular 2中使用Angular 1组件型指令的情况。
:marked
#### Change Detection
#### 变更检测
Change detection in Angular 1 is all about `scope.$apply()`. After every
event that occurs, `scope.$apply()` gets called. This is done either
automatically by the framework, or in some cases manually by our own
code. It is the point in time when change detection occurs and data
bindings get updated.
Angular 1中的变更检测全是关于`scope.$apply()`的。在每个事件发生之后,`scope.$apply()`就会被调用。
这或者由框架自动调用,或者在某些情况下由我们自己的代码手动调用。它是发生变更检测以及更新数据绑定的时间点。
In Angular 2 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 2 code runs inside something
called the [Angular zone](../api/core/index/NgZone-class.html). 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 2中事情有点不一样。虽然变更检测仍然会在每一个事件之后发生却不再需要每次调用`scope.$apply()`了。
这是因为所有Angular 2代码都运行在一个叫做[Angular zone](../api/core/index/NgZone-class.html)的地方。
Angular总是知道什么时候代码执行完了也就知道了它什么时候应该触发变更检测。代码本身并不需要调用`scope.$apply()`或其它类似的东西。
In the case of hybrid applications, the `UpgradeModule` bridges the
Angular 1 and Angular 2 approaches. Here's what happens:
在这种混合式应用的案例中,`UpgradeModule`在Angular 1的方法和Angular 2的方法之间建立了桥梁。发生了什么呢
* Everything that happens in the application runs inside the Angular 2 zone.
This is true whether the event originated in Angular 1 or Angular 2 code.
The zone triggers Angular 2 change detection after every event.
* 应用中发生的每件事都运行在Angular 2的zone里。
无论事件发生在Angular 1还是Angular 2的代码中都是如此。
* The `UpgradeModule` will invoke the Angular 1 `$rootScope.$apply()` after
every turn of the Angular zone. This also triggers Angular 1 change
detection after every event.
* `UpgradeModule`将在每一次离开Angular zone时调用Angular 1的`$rootScope.$apply()`。这样也就同样会在每个事件之后触发Angular 1的变更检测。
figure.image-display
img(src="/resources/images/devguide/upgrade/change_detection.png" alt="Change detection in a hybrid application" width="600")
:marked
What this means in practice is that we do not need to call `$apply()` in
our code, regardless of whether it is in Angular 1 on Angular 2. The
`UpgradeModule` does it for us. We *can* still call `$apply()` so there
is no need to remove such calls from existing code. Those calls just don't
have any effect in a hybrid application.
在实践中,这意味着我们不用在自己的代码中调用`$apply()`而不用管这段代码是在Angular 1还是Angular 2中。
`UpgradeModule`都替我们做了。我们仍然*可以*调用`$apply()`,也就是说我们不必从现有代码中移除此调用。
但是在混合式应用中,那些调用没有任何效果。
:marked
When we downgrade an Angular 2 component and then use it from Angular 1,
the component's inputs will be watched using Angular 1 change detection.
When those inputs change, the corresponding properties in the component
are set. We can also hook into the changes by implementing the
[OnChanges](../api/core/index/OnChanges-class.html) interface in the component,
just like we could if it hadn't been downgraded.
当我们降级一个Angular 2组件然后把它用于Angular 1中时组件的输入属性就会被Angular 1的变更检测体系监视起来。
当那些输入属性发生变化时,组件中相应的属性就会被设置。我们也能通过实现[OnChanges](../api/core/index/OnChanges-interface.html)
接口来挂钩到这些更改,就像它未被降级时一样。
Correspondingly, when we upgrade an Angular 1 component and use it from Angular 2,
all the bindings defined for the component directive's `scope` (or `bindToController`)
will be hooked into Angular 2 change detection. They will be treated
as regular Angular 2 inputs and set onto the scope (or controller) when
they change.
相应的当我们把Angular 1的组件升级给Angular 2使用时在这个组件型指令的`scope`(或`bindToController`)中定义的所有绑定,
都将被挂钩到Angular 2的变更检测体系中。它们将和标准的Angular 2输入属性被同等对待并当它们发生变化时设置回scope(或控制器)上。
### Using UpgradeModule with Angular 2 _NgModules_
### 通过Angular 2的*NgModule*来使用UpgradeModule
Both Angular 1 and Angular 2 have their own concept of modules
to help organize an application into cohesive blocks of funcionality.
Angular 1还是Angular 2都有自己的模块概念来帮你我们把应用组织成一些紧密相关的功能块。
Their details are quite different in architecture and implementation.
In Angular 1, you add Angular assets to the `angular.module` property.
In Angular 2, you create one or more classes adorned with an `NgModule` decorator
that describes Angular assets in metadata. The differences blossom from there.
它们在架构和实现的细节上有着显著的不同。
在Angular 1中我们会把Angular 1的资源添加到`angular.module`属性上。
在Angular 2中我们会创建一个或多个带有`NgModule`装饰器的类这些装饰器用来在元数据中描述Angular资源。差异主要来自这里。
In a hybrid application we run both versions of Angular at the same time.
That means that we need at least one module each from both Angular 1 and Angular 2.
We will import `UpgradeModule` inside our Angular 2 module, and then use it for
bootstrapping our Angular 1 module. Let's see how.
在混合式应用中我们同时运行了两个版本的Angular。
这意味着我们至少需要Angular 1和Angular 2各提供一个模块。
当我们使用Angular 1的模块进行引导时就得把Anuglar 2的模块传给`UpgradeModule`。我们来看看怎么做。
.l-sub-section
:marked
Learn more about Angular 2 modules at the [NgModule guide](ngmodule.html).
要了解Angular 2模块的更多信息请参阅[Angular模块](ngmodule.html)页。
:marked
### Bootstrapping Hybrid Angular 1+2 Applications
### 引导Angular 1+2的混合式应用程序
The first step to upgrading an application using the `UpgradeModule` is
always to bootstrap it as a hybrid that supports both Angular 1 and
Angular 2.
使用`UpgradeModule`升级应用的第一步总是把它引导成一个同时支持Angular 1和Angular 2的混合式应用。
Pure Angular 1 applications can be bootstrapped in two ways: By using an `ng-app`
directive somewhere on the HTML page, or by calling
[angular.bootstrap](https://docs.angularjs.org/api/ng/function/angular.bootstrap)
from JavaScript. In Angular 2, only the second method is possible - there is
no `ng-app` in Angular 2. This is also the case for hybrid applications.
Therefore, it is a good preliminary step to switch Angular 1 applications to use the
JavaScript bootstrap method even before switching them to hybrid mode.
纯粹的Angular 1应用可以用两种方式引导在HTML页面中的某处使用`ng-app`指令或者从JavaScript中调用
[angular.bootstrap](https://docs.angularjs.org/api/ng/function/angular.bootstrap)。
在Angular 2中只有第二种方法是可行的因为它没有`ng-app`指令。在混合式应用中也同样只能用第二种方法。
所以在将Angular 1应用切换到混合模式之前把它改为用JavaScript引导的方式是一个不错的起点。
Say we have an `ng-app` driven bootstrap such as this one:
比如说我们有个由`ng-app`驱动的引导过程,就像这个:
+makeExample('upgrade-module/ts/index-ng-app.html', null, null, {otl: /(ng-app.*ng-strict-di)/})
:marked
We 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`,它能达到同样效果:
+makeExample('upgrade-module/ts/app/1-bootstrap/app.module.ts', 'bootstrap')
:marked
Now introduce Angular 2 to the project. Inspired by instructions in
[the QuickStart](../quickstart.html), you can selectively copy in material from the
<a href="https://github.com/angular/quickstart" target="_blank">QuickStart github repository</a>.
现在把Angular 2引入项目中。根据[“快速起步”](../quickstart.html)中的指导,你可以有选择的从<a href="https://github.com/angular/quickstart" target="_blank">“快速起步”的Github仓库</a>中拷贝素材进来。
Next, create an `app.module.ts` file and add the following `NgModule` class:
接下来,创建一个`app.module.ts`文件,并添加下列`NgModule`类:
+makeExample('upgrade-module/ts/app/1-2-hybrid-bootstrap/app.module.ts', 'ngmodule')
:marked
This bare minimum `NgModule` imports `BrowserModule`, the module every Angular browser-based app must have.
这个最小化的`NgModule`导入了`BrowserModule`该模块是每个基于浏览器的Angular应用都必须具备的。
It also imports `UpgradeModule` from `@angular/upgrade/static`, and adds an override to prevent
Angular 2 from bootstrapping itself in the form of the `ngDoBootstrap` empty class method.
它还从`@angular/upgrade/static`导入了`UpgradeModule`,并添加了一个`ngDoBootstrap`空的覆盖方法,防止
Angular 2启动它自身。
Now we bootstrap `AppModule` using `platformBrowserDynamic`'s `bootstrapModule` method.
Then we use dependency injection to get a hold of the `UpgradeModule` instance in `AppModule`,
and use it to bootstrap our Angular 1 app.
The `upgrade.bootstrap` method takes the exact same arguments as [angular.bootstrap](https://docs.angularjs.org/api/ng/function/angular.bootstrap):
现在我们使用`platformBrowserDynamic`的`bootstrapModule`方法启动`AppModule`。
接着我们使用依赖注入来获取`AppModule`中的一个`UpgradeModule`实例,
并使用它来启动我们的Angular 1应用。
`upgrade.bootstrap`方法接受与[angular.bootstrap](https://docs.angularjs.org/api/ng/function/angular.bootstrap)相同的参数。
+makeExample('upgrade-module/ts/app/1-2-hybrid-bootstrap/app.module.ts', 'bootstrap')
:marked
Congratulations! You're running a hybrid Angular 1+2 application! The
existing Angular 1 code works as before _and_ you're ready to run Angular 2 code.
恭喜我们就要开始运行Angular 1+2的混合式应用程序了所有现存的Angular 1代码会像以前一样正常工作但是我们现在也同样可以运行Angular 2代码了。
:marked
### Using Angular 2 Components from Angular 1 Code
### 在Angular 1的代码中使用Angular 2的组件
figure
img(src="/resources/images/devguide/upgrade/a1-to-a2.png" alt="Using an Angular 2 component from Angular 1 code" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
Once we're running a hybrid app, we can start the gradual process of upgrading
code. One of the more common patterns for doing that is to use an Angular 2 component
in an Angular 1 context. This could be a completely new component or one that was
previously Angular 1 but has been rewritten for Angular 2.
一旦我们开始运行混合式应用我们就可以开始逐渐升级代码了。做这件事的一种更常见的模式就是在Angular 1的上下文中使用Angular 2的组件。
该组件可能是全新的也可能是把原本Angular 1的组件用Angular 2重写而成的。
Say we have a simple Angular 2 component that shows information about a hero:
假设我们有一个简单的用来显示英雄信息的Angular 2组件
+makeExample('upgrade-module/ts/app/downgrade-static/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
If we want to use this component from Angular 1, we need to *downgrade* it
using the `downgradeComponent()` method. What we get when we do that is an Angular 1
*directive*, which we can then register into our Angular 1 module:
如果我们想在Angular 1中使用这个组件我们就得用`downgradeComponent()`方法把它*降级*。
如果我们这么做就会得到一个Angular 1的*指令*我们可以把它注册到Angular 1的模块中
+makeExample('upgrade-module/ts/app/downgrade-static/app.module.ts', 'downgradecomponent')
:marked
Because `HeroDetailComponent` is an Angular 2 component, we must also add it to the
`declarations` in the `AppModule`.
由于`HeroDetailComponent`是一个Angular 2组件所以我们必须同时把它加入`AppModule`的`declarations`字段中。
And because this component is being used from the Angular 1 module, and is an entry point into
our Angular 2 application, we also need to add it to the `entryComponents` for our
Angular 2 module.
并且由于这个组件在Angular 1模块中使用也是我们Angular 2应用的一个入口点我们还需要
将它加入到Angular 2模块的`entryComponents`列表中。
+makeExample('upgrade-module/ts/app/downgrade-static/app.module.ts', 'ngmodule')
.l-sub-section
:marked
All Angular 2 components, directives and pipes must be declared in an NgModule.
所有Angular 2组件、指令和管道都必须声明在NgModule中。
:marked
The net resulit is an Angular 1 directive called `heroDetail`, that we can
use like any other directive in our Angular 1 templates.
这里我们得到的是一个叫做`heroDetail`的Angular 1指令我们可以像用其它指令一样把它用在Angular 1模板中。
+makeExample('upgrade-module/ts/index-downgrade-static.html', 'usecomponent')
.alert.is-helpful
:marked
Note that this Angular 1 is an element directive (`restrict: 'E'`) called `heroDetail`.
An Angular 1 element directive is matched based on its _name_.
*The `selector` metadata of the downgraded Angular 2 component is ignored.*
注意它在Angular 1中是一个名叫`heroDetail`的元素型指令(`restrict: 'E'`)。
Angular 1的元素型指令是基于它的*名字*匹配的。
*Angular 2组件中的`selector`元数据,在降级后的版本中会被忽略。*
:marked
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 2 hero detail component with inputs and outputs might look
like this:
当然,大多数组件都不像这个这么简单。它们中很多都有*输入属性和输出属性*,来把它们连接到外部世界。
Angular 2的英雄详情组件带有像这样的输入属性与输出属性
+makeExample('upgrade-module/ts/app/downgrade-io/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
These inputs and outputs can be supplied from the Angular 1 template, and the
`downgradeComponent()` method takes care of bridging them over via the `inputs`
and `outputs` arrays:
这些输入属性和输出属性的值来自于Angular 1的模板而`downgradeComponent()`方法负责桥接它们:
+makeExample('upgrade-module/ts/app/downgrade-io/app.module.ts', 'downgradecomponent')
+makeExample('upgrade-module/ts/index-downgrade-io.html', 'usecomponent')
:marked
Note that even though we are in an Angular 1 template, **we're using Angular 2
attribute syntax to bind the inputs and outputs**. This is a requirement for downgraded
components. The expressions themselves are still regular Angular 1 expressions.
注意虽然我们正在Angular 1的模板中**但却在使用Angular 2的属性(Attribute)语法来绑定到输入属性与输出属性**。
这是降级的组件本身要求的。而表达式本身仍然是标准的Angular 1表达式。
.callout.is-important
header Use kebab-case for downgraded component attributes
header 在降级过的组件属性中使用中线命名法
:marked
There's one notable exception to the rule of using Angular 2 attribute syntax
for downgraded components. It has to do with input or output names that consist
of multiple words. In Angular 2 we would bind these attributes using camelCase:
为降级过的组件使用Angular 2的属性(Attribute)语法规则时有一个值得注意的例外。
它适用于由多个单词组成的输入或输出属性。在Angular 2中我们要使用小驼峰命名法绑定这些属性
code-example(format="").
[myHero]="hero"
:marked
But when using them from Angular 1 templates, we need to use kebab-case:
但是从Angular 1的模板中使用它们时我们得使用中线命名法
code-example(format="").
[my-hero]="hero"
:marked
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 Angular 1 template, we can still use other Angular 1
directives on the element, even though it has Angular 2 binding attributes on it.
For example, we can easily make multiple copies of the component using `ng-repeat`:
由于这是一个Angular 1模板虽然它已经有了Angular 2中绑定的属性(Attribute)我们仍可以在这个元素上使用其它Angular 1指令。
例如,我们可以用`ng-repeat`简单的制作该组件的多份拷贝:
+makeExample('upgrade-module/ts/index-downgrade-io.html', 'userepeatedcomponent')
:marked
### Using Angular 1 Component Directives from Angular 2 Code
### 从Angular 2代码中使用Angular 1组件型指令
figure
img(src="/resources/images/devguide/upgrade/a2-to-a1.png" alt="Using an Angular 1 component from Angular 2 code" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
So, we can write an Angular 2 component and then use it from Angular 1
code. This is very useful when we start our migration from lower-level
components and work our 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 our way down. This too can be done using the `UpgradeModule`.
We can *upgrade* Angular 1 component directives and then use them from
Angular 2.
现在我们已经能在Angular 2中写一个组件并把它用于Angular 1代码中了。
当我们从低级组件开始移植,并往上走时,这非常有用。但在另外一些情况下,从相反的方向进行移植会更加方便:
从高级组件开始,然后往下走。这也同样能用`UpgradeModule`完成。
我们可以*升级*Angular 1组件型指令然后从Angular 2中用它们。
Not all kinds of Angular 1 directives can be upgraded. The directive
really has to be a *component directive*, with the characteristics
[described in the preparation guide above](#using-component-directives).
Our safest bet for ensuring compatibility is using the
[component API](https://docs.angularjs.org/api/ng/type/angular.Module)
introduced in Angular 1.5.
不是所有种类的Angular 1指令都能升级。该指令必须是一个严格的*组件型指令*,具有[上面的准备指南中描述的](#using-component-directives)那些特征。
确保兼容性的最安全的方式是Angular 1.5中引入的[组件API](https://docs.angularjs.org/api/ng/type/angular.Module)。
A simple example of an upgradable component is one that just has a template
and a controller:
可升级组件的简单例子是只有一个模板和一个控制器的指令:
+makeExample('upgrade-module/ts/app/upgrade-static/hero-detail.component.ts', 'hero-detail', 'hero-detail.component.ts')
:marked
We can *upgrade* this component to Angular 2 using the `UpgradeComponent` class.
By creating a new Angular 2 **directive** that extends `UpgradeComponent` and doing a `super` call
inside it's constructor, we have a fully upgrade Angular 1 component to be used inside Angular 2.
All that is left is to add it to `AppModule`'s `declarations` array.
我们可以使用`UpgradeComponent`方法来把这个组件*升级*到Angular 2。
具体方法是创建一个Angular 2**指令**,继承`UpgradeComponent在其构造函数中进行`super`调用,
这样我们就得到一个完全升级的Angular 1组件并且可以Angular 2中使用。
剩下是工作就是把它加入到`AppModule`的`declarations`数组。
+makeExample('upgrade-module/ts/app/upgrade-static/hero-detail.component.ts', 'hero-detail-upgrade', 'hero-detail.component.ts')
+makeExample('upgrade-module/ts/app/upgrade-static/app.module.ts', 'hero-detail-upgrade', 'hero-detail.component.ts')
.alert.is-helpful
:marked
Upgraded componentes are Angular 2 **directives**, instead of **components**, because Angular 2
is unaware that Angular 1 will create elements under it. As far as Angular 2 knows, the upgraded
component is just a directive - a tag - and Angular 2 doesn't have to concern itself with
it's children.
升级后的组件是Angular 2的**指令**,而不是**组件**因为Angular 2不知道Angular 1将在它下面创建元素。
Angular 2所知道的是升级后的组件只是一个指令一个标签Angular 2不需要关心组件本身及其子元素。
:marked
An upgraded component may also have inputs and outputs, as defined by
the scope/controller bindings of the original Angular 1 component
directive. When we use the component from an Angular 2 template,
we provide the inputs and outputs using **Angular 2 template syntax**,
with the following rules:
升级后的组件也可能有输入属性和输出属性它们是在原Angular 1组件型指令的scope/controller绑定中定义的。
当我们从Angular 2模板中使用该组件时我们要使用**Angular 2模板语法**来提供这些输入属性和输出属性,但要遵循下列规则:
table
tr
th
th
p Binding definition
p 绑定定义
th
p Template syntax
p 模板语法
tr
th
p Attribute binding
p 属性(Attribute)绑定
td
:marked
`myAttribute: '@myAttribute'`
td
:marked
`<my-component myAttribute="value">`
tr
th
p Expression binding
p 表达式绑定
td
:marked
`myOutput: '&myOutput'`
td
:marked
`<my-component (myOutput)="action()">`
tr
th
p One-way binding
p 单向绑定
td
:marked
`myValue: '<myValue'`
td
:marked
`<my-component [myValue]="anExpression">`
tr
th
p Two-way binding
p 双向绑定
td
:marked
`myValue: '=myValue'`
td
:marked
As a two-way binding: `<my-component [(myValue)]="anExpression">`.
Since most Angular 1 two-way bindings actually only need a one-way binding
in practice, `<my-component [myValue]="anExpression">` is often enough.
用作输入:`<my-component [myValue]="anExpression">` 或
用作双向绑定:`<my-component [(myValue)]="anExpression"`
:marked
As an example, say we have a hero detail Angular 1 component directive
with one input and one output:
举个例子假设我们在Angular 1中有一个表示“英雄详情”的组件型指令它带有一个输入属性和一个输出属性
+makeExample('upgrade-module/ts/app/upgrade-io/hero-detail.component.ts', 'hero-detail-io', 'hero-detail.component.ts')
:marked
We can upgrade this component to Angular 2, annotate inputs and outputs in the upgrade directive,
and then provide the input and output using Angular 2 template syntax:
我们可以把这个组件升级到Angular 2然后使用Angular 2的模板语法提供这个输入属性和输出属性
+makeExample('upgrade-module/ts/app/upgrade-io/hero-detail.component.ts', 'hero-detail-io-upgrade', 'hero-detail.component.ts')
+makeExample('upgrade-module/ts/app/upgrade-io/container.component.ts', null, 'container.component.ts')
:marked
### Projecting Angular 1 Content into Angular 2 Components
### 把Angular 1的内容投影到Angular 2组件中
figure
img(src="/resources/images/devguide/upgrade/a1-to-a2-with-projection.png" alt="Projecting Angular 1 content into Angular 2" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
When we are using a downgraded Angular 2 component from an Angular 1
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 2,
there is a very similar concept called *content projection*. The `UpgradeModule`
is able to make these two features interoperate.
如果我们在Angular 1模板中使用降级后的Angular 2组件时可能会需要把模板中的一些内容投影进那个组件。
这也是可能的虽然在Angular 2中并没有透传(transclude)这样的东西,但它有一个非常相似的概念,叫做*内容投影*。
`UpgradeModule`也能让这两个特性实现互操作。
Angular 2 components that support content projection make use of an `<ng-content>`
tag within them. Here's an example of such a component:
Angular 2的组件通过使用`<ng-content>`标签来支持内容投影。下面是这类组件的一个例子:
+makeExample('upgrade-module/ts/app/1-to-2-projection/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
When using the component from Angular 1, we can supply contents for it. Just
like they would be transcluded in Angular 1, they get projected to the location
of the `<ng-content>` tag in Angular 2:
当从Angular 1中使用该组件时我们可以为它提供内容。正如它们将在Angular 1中被透传一样
它们也在Angular 2中被投影到了`<ng-content>`标签所在的位置:
+makeExample('upgrade-module/ts/index-1-to-2-projection.html', 'usecomponent')
.alert.is-helpful
:marked
When Angular 1 content gets projected inside an Angular 2 component, it still
remains in "Angular 1 land" and is managed by the Angular 1 framework.
当Angular 1的内容被投影到Angular 2组件中时它仍然留在“Angular 1王国”中并被Angular 1框架管理着。
:marked
### Transcluding Angular 2 Content into Angular 1 Component Directives
### 把Angular 2的内容透传进Angular 1的组件型指令
figure
img(src="/resources/images/devguide/upgrade/a2-to-a1-with-transclusion.png" alt="Projecting Angular 2 content into Angular 1" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
Just like we can project Angular 1 content into Angular 2 components,
we can *transclude* Angular 2 content into Angular 1 components, whenever
we are using upgraded versions from them.
就像我们能把Angular 1的内容投影进Angular 2组件一样我们也能把Angular 2的内容*透传*进Angular 1的组件
但不管怎样,我们都要使用它们升级过的版本。
When an Angular 1 component directive supports transclusion, it may use
the `ng-transclude` directive in its template to mark the transclusion
point:
如果一个Angular 1组件型指令支持透传它就会在自己的模板中使用`ng-transclude`指令标记出透传到的位置:
+makeExample('upgrade-module/ts/app/2-to-1-transclusion/hero-detail.component.ts', null, 'hero-detail.component.ts')
.alert.is-helpful
:marked
The directive also needs to have the `transclude: true` option enabled.
It is on by default for component directives defined with the
1.5 component API.
该指令还需要启用一个`transclude: true`选项。当用Angular 1.5中的组件API定义组件型指令时该选项默认是开启的。
:marked
If we upgrade this component and use it from Angular 2, we can populate
the component tag with contents that will then get transcluded:
如果我们升级这个组件并把它用在Angular 2中我们就能把准备透传的内容放进这个组件的标签中。
+makeExample('upgrade-module/ts/app/2-to-1-transclusion/container.component.ts', null, 'container.component.ts')
:marked
### Making Angular 1 Dependencies Injectable to Angular 2
### 让Angular 1中的依赖可被注入到Angular 2
When running a hybrid app, we may bump into situations where we need to have
some Angular 1 dependencies to be injected to Angular 2 code. This may be
because we have some business logic still in Angular 1 services, or because
we need some of Angular 1's built-in services like `$location` or `$timeout`.
当运行一个混合式应用时我们可能会遇到这种情况我们需要把某些Angular 1的依赖注入到Angular 2代码中。
这可能是因为某些业务逻辑仍然在Angular 1服务中或者需要某些Angular 1的内置服务比如`$location`或`$timeout`。
In these situations, it is possible to *upgrade* an Angular 1 provider to
Angular 2. This makes it possible to then inject it somewhere in Angular 2
code. For example, we might have a service called `HeroesService` in Angular 1:
在这些情况下把一个Angular 1提供商*升级到*Angular 2也是有可能的。这就让它将来有可能被注入到Angular 2代码中的某些地方。
比如我们可能在Angular 1中有一个名叫`HeroesService`的服务:
+makeExample('upgrade-module/ts/app/1-to-2-providers/heroes.service.ts', null, 'heroes.service.ts')
:marked
We can upgrade the service using a Angular 2 [Factory provider](../guide/dependency-injection.html#factory-providers)
that requests the service from the Angular 1 `$injector`. The name of the Angular 2 dependency is up to you:
我们可以Angular 2的[工厂提供商factory provider](../guide/dependency-injection.html#factory-providers)升级该服务,
它从Angular 1的`$injector`请求服务。Angular 2依赖的名称由你确定
+makeExample('upgrade-module/ts/app/1-to-2-providers/app.module.ts', 'register', 'app.module.ts')
:marked
We can then inject it in Angular 2 using a string token:
然后我们可以一个字符串型令牌把它注入到Angular 2中
+makeExample('upgrade-module/ts/app/1-to-2-providers/hero-detail.component.ts', null, 'hero-detail.component.ts')
.alert.is-helpful
:marked
In this example we upgraded a service class, which has the added benefit that
we can use a TypeScript type annotation when we 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 Angular 1 service, factory, or
provider can be upgraded.
在这个例子中我们升级了服务类。当我们注入它时我们可以使用TypeScript类型注解来获得这些额外的好处。
它没有影响该依赖的处理过程,同时还得到了启用静态类型检查的好处。
任何Angular 1中的服务、工厂和提供商都能被升级 —— 尽管这不是必须的。
:marked
### Making Angular 2 Dependencies Injectable to Angular 1
### 让Angular 2的依赖能被注入到Angular 1中
In addition to upgrading Angular 1 dependencies, we can also *downgrade*
Angular 2 dependencies, so that we can use them from Angular 1. This can be
useful when we start migrating services to Angular 2 or creating new services
in Angular 2 while we still have components written in Angular 1.
除了能升级Angular 1依赖之外我们还能*降级*Angular 2的依赖以便我们能在Angular 1中使用它们。
当我们已经开始把服务移植到Angular 2或在Angular 2中创建新服务但同时还有一些用Angular 1写成的组件时这会非常有用。
For example, we might have an Angular 2 service called `Heroes`:
例如我们可能有一个Angular 2的`Heroes`服务:
+makeExample('upgrade-module/ts/app/2-to-1-providers/heroes.ts', null, 'heroes.ts')
:marked
Again, as with Angular 2 components, register the provider with the `NgModule` by adding it to the module's `providers` list.
仿照Angular 2组件我们通过把该提供商加入`NgModule`的`providers`列表中来注册它。
+makeExample('upgrade-module/ts/app/2-to-1-providers/app.module.ts', 'ngmodule', 'app.module.ts')
:marked
Now wrap the Angular 2 `Heroes` in an *Angular 1 factory function* using `downgradeInjectable()`.
and plug the factory into an Angular 1 module.
The name of the Angular 1 dependency is up to you:
现在,我们使用`upgradeAdapter.downgradeNg2Provider()`来把Angular 2的`Heroes`包装成*Angular 1的工厂函数*并把这个工厂注册进Angular 1的模块中。
依赖在Angular 1中的名字你可以自己定
+makeExample('upgrade-module/ts/app/2-to-1-providers/app.module.ts', 'register', 'app.module.ts')
:marked
After this, the service is injectable anywhere in our Angular 1 code:
此后该服务就能被注入到Angular 1代码中的任何地方了
+makeExample('upgrade-module/ts/app/2-to-1-providers/hero-detail.component.ts', null, 'hero-detail.component.ts')
.l-main-section
:marked
## PhoneCat Upgrade Tutorial
## PhoneCat升级教程
In this section and we will look at a complete example of
preparing and upgrading an application using the `upgrade` module. The app
we're going to work on is [Angular PhoneCat](https://github.com/angular/angular-phonecat)
from [the original Angular 1 tutorial](https://docs.angularjs.org/tutorial),
which is where many of us began our Angular adventures. Now we'll see how to
bring that application to the brave new world of Angular 2.
在本节和下节中,我们将看一个完整的例子,它使用`upgrade`模块准备和升级了一个应用程序。
该应用就是来自[原Angular 1教程](https://docs.angularjs.org/tutorial)中的[Angular PhoneCat](https://github.com/angular/angular-phonecat)。
那是我们很多人当初开始Angular探险之旅的起点。
现在我们来看看如何把该应用带入Angular 2的美丽新世界。
During the process we'll learn how to apply the steps outlined in the
[preparation guide](#preparation) in practice: We'll align the application
with Angular 2 and also take TypeScript into use.
这期间,我们将学到如何在实践中应用[准备指南](#preparation)中列出的那些重点步骤:
我们先让该应用向Angular 2看齐然后为它引入SystemJS模块加载器和TypeScript。
To follow along with the tutorial, clone the
[angular-phonecat](https://github.com/angular/angular-phonecat) repository
and apply the steps as we go.
要跟随本教程,请先把[angular-phonecat](https://github.com/angular/angular-phonecat)仓库克隆到本地,并跟我们一起应用这些步骤。
In terms of project structure, this is where our work begins:
在项目结构方面,我们工作的起点是这样的:
.filetree
.file angular-phonecat
.children
.file bower.json
.file karma.conf.js
.file package.json
.file app
.children
.file core
.children
.file checkmark
.children
.file checkmark.filter.js
.file checkmark.filter.spec.js
.file phone
.children
.file phone.module.js
.file phone.service.js
.file phone.service.spec.js
.file core.module.js
.file phone-detail
.children
.file phone-detail.component.js
.file phone-detail.component.spec.js
.file phone-detail.module.js
.file phone-detail.template.html
.file phone-list
.children
.file phone-list.component.js
.file phone-list.component.spec.js
.file phone-list.module.js
.file phone-list.template.html
.file img
.children
.file ...
.file phones
.children
.file ...
.file app.animations.js
.file app.config.js
.file app.css
.file app.module.js
.file index.html
.file e2e-tests
.children
.file protractor-conf.js
.file scenarios.js
:marked
This is actually a pretty good starting point. The code uses the Angular 1.5
component API and the organization follows the
[Angular 1 Style Guide](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md),
which is an important [preparation step](#following-the-angular-style-guide) before
a successful upgrade.
这确实是一个很好地起点。特别是,该结构遵循了[Angular 1 风格指南](https://github.com/johnpapa/angular-styleguide)
要想成功升级,这是一个很重要的[准备步骤](#following-the-angular-style-guide)。
* Each component, service, and filter is in its own source file, as per the
[Rule of 1](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility).
* 每个组件、服务和过滤器都在它自己的源文件中 —— 就像[单一规则](https://github.com/johnpapa/angular-styleguide#single-responsibility)所要求的。
* The `core`, `phone-detail`, and `phone-list` modules are each in their
own subdirectory. Those subdirectories contain the JavaScript code as well as
the HTML templates that go with each particular feature. This is in line with the
[Folders-by-Feature Structure](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y152)
and [Modularity](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#modularity)
rules.
* `core`、`phone-detail`和`phone-list`模块都在它们自己的子目录中。那些子目录除了包含HTML模板之外还包含JavaScript代码它们共同完成一个特性。
这是[按特性分目录的结构](https://github.com/johnpapa/angular-styleguide#style-y152)
和[模块化](https://github.com/johnpapa/angular-styleguide#modularity)规则所要求的。
* Unit tests are located side-by-side with application code where they are easily
found, as described in the rules for
[Organizing Tests](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y197).
* 单元测试都和应用代码在一起,它们很容易找到。就像规则
[组织测试文件](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y197)中要求的那样。
:marked
### Switching to TypeScript
### 切换到TypeScript
Since we're going to be writing our Angular 2 code in TypeScript, it makes sense to
bring in the TypeScript compiler even before we begin upgrading.
因为我们将使用TypeScript编写Angular 2的代码所以在开始升级之前我们把TypeScript的编译器设置好是很合理的。
We will also start to gradually phase out the Bower package manager in favor
of NPM. We'll install all new dependencies using NPM, and will eventually be
able to remove Bower from the project.
我们还将开始逐步淘汰Bower包管理器换成我们更喜欢的NPM。后面我们将使用NPM来安装新的依赖包并最终从项目中移除Bower。
Let's begin by installing TypeScript to the project.
让我们先把TypeScript包安装到项目中。
code-example(format="").
npm i typescript --save-dev
:marked
Let's also add run scripts for the `tsc` TypeScript compiler to `package.json`:
我们还要把用来运行TypeScript编译器`tsc`和`typings`工具的脚本添加到`package.json`中:
+makeJson('upgrade-phonecat-1-typescript/ts/package.json', {paths: 'scripts.tsc, scripts.tsc:w'}, 'package.json')
:marked
We can now install type definitions for the existing libraries that
we're using but that don't come with prepackaged types: Angular 1 and the
Jasmine unit test framework.
现在我们可以使用typings工具来安装Angular 1和Jasmine单元测试框架的类型定义文件。
code-example(format="").
npm install @types/jasmine @types/angular @types/angular-animate @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev
:marked
We should also configure the TypeScript compiler so that it can understand our
project. We'll add a `tsconfig.json` file to the project directory, just like we do
in the [Quickstart](../quickstart.html). It instructs the TypeScript compiler how
to interpret our source files.
我们还应该配置TypeScript编译器以便它能理解我们的项目结构。我们要往项目目录下添加一个`tsconfig.json`文件,
就像在[“快速起步”](../quickstart.html)中做过的那样。它将告诉TypeScript编译器该如何编译我们的源文件。
+makeJson('upgrade-phonecat-1-typescript/ts/tsconfig.ng1.json', null, 'tsconfig.json')
:marked
We are telling the TypeScript compiler to turn our TypeScript files to ES5 code
bundled into CommonJS modules.
我们告诉TypeScript编译器把TypeScript文件转换成ES5代码并打包进CommonJS模块中。
We can now launch the TypeScript compiler from the command line. It will watch
our `.ts` source files and compile them to JavaScript on the fly. Those compiled
`.js` files are then loaded into the browser by SystemJS. This is a process we'll
want to have continuously running in the background as we go along.
我们现在可以从命令行启动TypeScript编译器。它将监控`.ts`源码文件并随时把它们编译成JavaScript。
然后这些编译出的`.js`文件被SystemJS加载到浏览器中。当我们继续往前走的时候这个过程将在后台持续运行。
code-example(format="").
npm run tsc:w
:marked
The next thing we'll do is convert our JavaScript files to TypeScript. Since
TypeScript is a superset of ECMAScript 2015, which in turn is a superset
of ECMAScript 5, we can simply switch the file extensions from `.js` to `.ts`
and everything will work just like it did before. As the TypeScript compiler
runs, it emits the corresponding `.js` file for every `.ts` file and the
compiled JavaScript is what actually gets executed. If you start
the project HTTP server with `npm start`, you should see the fully functional
application in your browser.
我们要做的下一件事是把JavaScript文件转换成TypeScript文件。
由于TypeScript是ECMAScript 2015的一个超集而ES2015又是ECMAScript 5的超集所以我们可以简单的把文件的扩展名从`.js`换成`.ts`
它们还是会像以前一样工作。由于TypeScript编译器仍在运行它会为每一个`.ts`文件生成对应的`.js`文件,而真正运行的是编译后的`.js`文件。
如果你用`npm start`开启了本项目的HTTP服务器你会在浏览器中看到一个功能完好的应用。
Now that we have TypeScript though, we can start benefiting from some of its
features. There's a lot of value the language can provide to Angular 1 applications.
有了TypeScript我们就可以从它的一些特性中获益了。此语言可以为Angular 1应用提供很多价值。
For one thing, TypeScript is a superset of ES2015. Any app that has previously
been written in ES5 - like the PhoneCat example has - can with TypeScript
start incorporating all of the JavaScript features that are new to ES2015.
These include things like `let`s and `const`s, arrow functions, default function
parameters, and destructuring assignments.
首先TypeScript是一个ES2015的超集。任何以前用ES5写的程序(就像PhoneCat范例)都可以开始通过TypeScript
纳入那些添加到ES2015中的新特性。
这包括`let`、`const`、箭头函数、函数默认参数以及解构(destructure)赋值。
Another thing we can do is start adding *type safety* to our code. This has
actually partially already happened because of the Angular 1 typings we installed.
TypeScript are checking that we are calling Angular 1 APIs correctly when we do
things like register components to Angular modules.
我们能做的另一件事就是把*类型安全*添加到代码中。这实际上已经部分完成了因为我们已经安装了Angular 1的类型定义。
当我们正确调用Angular 1的API时TypeScript会帮我们检查它 —— 比如往Angular模块中注册组件。
But we can also start adding *type annotations* for our own code to get even more
out of TypeScript's type system. For instance, we can annotate the checkmark
filter so that it explicitly expects booleans as arguments. This makes it clearer
what the filter is supposed to do.
我们还能开始把*类型注解*添加到自己的代码中来从TypeScript的类型系统中获得更多帮助。
比如,我们可以给`checkmark`过滤器加上注解,表明它期待一个`boolean`类型的参数。
这可以更清楚的表明此过滤器打算做什么
+makeExample('upgrade-phonecat-1-typescript/ts/app/core/checkmark/checkmark.filter.ts', null, 'app/core/checkmark/checkmark.filter.ts')
:marked
In the `Phone` service we can explicitly annotate the `$resource` service dependency
as an `angular.resource.IResourceService` - a type defined by the Angular 1 typings.
在`Phone`服务中,我们可以明确的把`$resource`服务声明为`angular.resource.IResourceService`一个Angular 1类型定义提供的类型。
+makeExample('upgrade-phonecat-1-typescript/ts/app/core/phone/phone.service.ts', null, 'app/core/phone/phone.service.ts')
:marked
We can apply the same trick to the application's route configuration file in `app.config.ts`,
where we are using the location and route services. By annotating them accordingly TypeScript
can verify we're calling their APIs with the correct kinds of arguments.
我们可以在应用的路由配置中使用同样的技巧那里我们用到了location和route服务。
一旦给它们提供了类型信息TypeScript就能检查我们是否在用类型的正确参数来调用它们了。
+makeExample('upgrade-phonecat-1-typescript/ts/app/app.config.ts', null, 'app/app.config.ts')
.l-sub-section
:marked
The [Angular 1.x type definitions](https://www.npmjs.com/package/@types/angular)
we installed are not officially maintained by the Angular team,
but are quite comprehensive. It is possible to make an Angular 1.x application
fully type-annotated with the help of these definitions.
我们用typings工具安装的这个[Angular 1.x类型定义文件](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/angularjs)
并不是由Angular开发组维护的但它也已经足够全面了。借助这些类型定义的帮助它可以为Angular 1.x程序加上全面的类型注解。
If this is something we wanted to do, it would be a good idea to enable
the `noImplicitAny` configuration option in `tsconfig.json`. This would
cause the TypeScript compiler to display a warning when there's any code that
does not yet have type annotations. We could use it as a guide to inform
us about how close we are to having a fully annotated project.
如果我们想这么做,那么在`tsconfig.json`中启用`noImplicitAny`配置项就是一个好主意。
这样如果遇到什么还没有类型注解的代码TypeScript编译器就会显示一个警告。
我们可以用它作为指南,告诉我们现在与一个完全类型化的项目距离还有多远。
:marked
Another TypeScript feature we can make use of is *classes*. In particular, we
can turn our component controllers into classes. That way they'll be a step
closer to becoming Angular 2 component classes, which will make our life
easier once we do the upgrade.
我们能用的另一个TypeScript特性是*类*。具体来讲,我们可以把控制器转换成类。
这种方式下我们离成为Angular 2组件类就又近了一步它会令我们的升级之路变得更简单。
Angular 1 expects controllers to be constructor functions. That's exactly what
ES2015/TypeScript classes are under the hood, so that means we can just plug in a
class as a component controller and Angular 1 will happily use it.
Angular 1期望控制器是一个构造函数。这实际上就是ES2015/TypeScript中的类
这也就意味着只要我们把一个类注册为组件控制器Angular 1就会愉快的使用它。
Here's what our new class for the phone list component controller looks like:
新的“电话列表(phone list)”组件控制器类看起来是这样的:
+makeExample('upgrade-phonecat-1-typescript/ts/app/phone-list/phone-list.component.ts', null, 'app/phone-list/phone-list.component.ts')
:marked
What was previously done in the controller function is now done in the class
constructor function. The dependency injection annotations are attached
to the class using a static property `$inject`. At runtime this becomes the
`PhoneListController.$inject` property.
以前在控制器函数中实现的一切,现在都改由类的构造函数来实现了。类型注入注解通过静态属性`$inject`
被附加到了类上。在运行时,它们变成了`PhoneListController.$inject`。
The class additionally declares three members: The array of phones, the name of
the current sort key, and the search query. These are all things we have already
been attaching to the controller but that weren't explicitly declared anywhere.
The last one of these isn't actually used in the TypeScript code since it's only
referred to in the template, but for the sake of clarity we want to define all the
members our controller will have.
该类还声明了另外三个成员:电话列表、当前排序键的名字和搜索条件。
这些东西我们以前就加到了控制器上只是从来没有在任何地方显式定义过它们。最后一个成员从未真正在TypeScript代码中用过
因为它只是在模板中被引用过。但为了清晰起见,我们还是应该定义出此控制器应有的所有成员。
In the Phone detail controller we'll have two members: One for the phone
that the user is looking at and another for the URL of the currently displayed image:
在电话详情控制器中,我们有两个成员:一个是用户正在查看的电话,另一个是正在显示的图像:
+makeExample('upgrade-phonecat-1-typescript/ts/app/phone-detail/phone-detail.component.ts', null, 'app/phone-detail/phone-detail.component.ts')
:marked
This makes our controller code look a lot more like Angular 2 already. We're
all set to actually introduce Angular 2 into the project.
这已经让我们的控制器代码看起来更像Angular 2了。我们的准备工作做好了可以引进Angular 2到项目中了。
If we had any Angular 1 services in the project, those would also be
a good candidate for converting to classes, since like controllers,
they're also constructor functions. But we only have the `Phone` factory
in this project, and that's a bit special since it's an `ngResource`
factory. So we won't be doing anything to it in the preparation stage.
We'll instead turn it directly into an Angular 2 service.
如果项目中有任何Angular 1的服务它们也是转换成类的优秀候选人像控制器一样它们也是构造函数。
但是在本项目中,我们只有一个`Phone`工厂,这有点特别,因为它是一个`ngResource`工厂。
所以我们不会在准备阶段中处理它而是在下一节中直接把它转换成Angular 2服务。
### Installing Angular 2
### 安装Angular 2
Having completed our preparation work, let's get going with the Angular 2
upgrade of PhoneCat. We'll do this incrementally with the help of the
[upgrade module](#upgrading-with-the-upgrade-module) that comes with Angular 2.
By the time we're done, we'll be able to remove Angular 1 from the project
completely, but the key is to do this piece by piece without breaking the application.
我们已经完成了准备工作接下来就开始把PhoneCat升级到Angular 2。
我们将在Angular 2[升级模块](#upgrading-with-the-upgrade-adapter)的帮助下增量式的完成此项工作。
等我们完成的那一刻就能把Angular 1从项目中完全移除了但其中的关键是在不破坏此程序的前提下一小块一小块的完成它。
.alert.is-important
:marked
The project also contains some animations, which we are not yet upgrading in this version of the guide. This will change in a later release.
该项目还包含一些动画,在此指南的当前版本我们先不升级它,等到后面的发行版再改。
:marked
Let's install Angular 2 into the project, along with the SystemJS module loader. Take a look into the
[Quickstart](../quickstart.html) guide and get the following configurations from there:
我们来使用SystemJS模块加载器把Angular 2安装到项目中。
看看[“快速起步”](../quickstart.html)中的指南,并从那里获得如下配置:
* Add Angular 2 and the other new dependencies to `package.json`
* 把Angular 2和其它新依赖添加到`package.json`中
* The SystemJS configuration file `systemjs.config.js` to the project root directory.
* 把SystemJS的配置文件`systemjs.config.js`添加到项目的根目录。
Once these are done, run:
这些完成之后,就运行:
code-example(format="").
npm install
:marked
We can soon load Angular 2 dependencies into the application via `index.html`,
but first we need to do some directory path adjustments. This is because we're going
to need to load files from `node_modules` and the project root, whereas so far
in this project everything has been loaded from the `/app` directory.
我们可以通过`index.html`来把Angular 2的依赖快速加载到应用中
但首先,我们得做一些目录结构调整。这是因为我们正准备从`node_modules`中加载文件,然而目前项目中的每一个文件都是从`/app`目录下加载的。
Move the `app/index.html` file to the project root directory. Then change the
development server root path in `package.json` to also point to the project root
instead of `app`:
把`app/index.html`移入项目的根目录,然后把`package.json`中的开发服务器根目录也指向项目的根目录,而不再是`app`目录:
+makeJson('upgrade-phonecat-2-hybrid/ts/package.ng1.json', {paths: 'scripts.start'}, 'package.json (start script)')
:marked
Now we're able to serve everything from the project root to the web browser. But we do *not*
want to have to change all the image and data paths used in the application code to match
our development setup. For that reason, we'll add a `<base>` tag to `index.html`, which will
cause relative URLs to be resolved back to the `/app` directory:
现在,我们能把项目根目录下的每一样东西发给浏览器了。但我们不想为了适应开发环境中的设置,被迫修改应用代码中用到的所有图片和数据的路径。因此,我们往`index.html`中添加一个`<base>`标签,它将导致各种相对路径被解析回`/app`目录:
+makeExample('upgrade-phonecat-2-hybrid/ts/index.html', 'base', 'index.html')
:marked
Now we can load Angular 2 via SystemJS. We'll add the Angular 2 polyfills and the
SystemJS config to the end of the `<head>` section, and then we'll use `System.import`
to load the actual application:
现在我们可以通过SystemJS加载Angular 2了。我们将把Angular 2的填充库(polyfills)
和SystemJS的配置加到`<head>`区的末尾,然后,我们就用`System.import`来加载实际的应用:
+makeExample('upgrade-phonecat-2-hybrid/ts/index.html', 'ng2', 'index.html')
:marked
In the `systemjs.config.js` file we got from the Quickstart we also need to make a couple
of adjustments because of our project structure. We want to point the browser to the project
root when loading things through SystemJS, instead of using the `<base>` URL:
在我们从“快速起步”中拿来的`systemjs.config.js`文件中,我们还需要做一些调整,以适应我们的项目结构。
在使用SystemJS而不是`<base>` URL加载时我们需要把浏览器指向项目的根目录。
+makeExample('upgrade-phonecat-2-hybrid/ts/systemjs.config.1.js', 'paths', 'systemjs.config.js')
:marked
### Creating the _AppModule_
### 创建*AppModule*
Now create the root `NgModule` class called `AppModule`.
There is already a file named `app.module.ts` that holds the Angular 1 module.
Rename it to `app.module.ng1.ts` and update the corresponding script name in the `index.html` as well.
The file contents remain:
现在,创建一个名叫`AppModule`的根`NgModule`类。
我们已经有了一个名叫`app.module.ts`的文件其中存放着Angular 1的模块。
把它改名为`app.module.ng1.ts`,同时也要在`index.html`中更新对应的脚本名。
文件的内容保留:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ng1.ts', null, 'app.module.ng1.ts')
:marked
Now create a new `app.module.ts` with the minimum `NgModule` class:
然后创建一个新的`app.module.ts`文件,其中是一个最小化的`NgModule`类:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'bare', 'app.module.ts')
:marked
### Bootstrapping a hybrid 1+2 PhoneCat
### 引导PhoneCat的1+2混合式应用
What we'll do next is bootstrap the application as a *hybrid application*
that supports both Angular 1 and Angular 2 components. Once we've done that
we can start converting the individual pieces to Angular 2.
接下来我们把该应用程序引导改装为一个同时支持Angular 1和Angular 2的*混合式应用*。
然后就能开始把这些不可分割的小块转换到Angular 2了。
To [bootstrap a hybrid application](#bootstrapping-hybrid-angular-1-2-applications),
we first need to import `UpgradeModule` in our `AppModule`, and override it's bootstrap method:
要引导一个[混合式应用程序](#bootstrapping-hybrid-angular-1-2-applications)
我们首先需要在`AppModule`中导入`UpgradeModule并覆盖它的启动方法
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'upgrademodule', 'app/app.module.ts')
:marked
Our application is currently bootstrapped using the Angular 1 `ng-app` directive
attached to the `<html>` element of the host page. This will no longer work with
Angular 2. We should switch to a JavaScript-driven bootstrap instead.
我们的应用现在是使用宿主页面中附加到`<html>`元素上的`ng-app`指令引导的。
但在Angular 2中它不再工作了。我们得切换成JavaScript驱动的引导方式。
So, remove the `ng-app` attribute from `index.html`, and instead boostrap via `app/main.ts`.
This file has been configured as the application entrypoint in `systemjs.config.js`,
so it is already being loaded by the browser.
所以,从`index.html`中移除`ng-app`属性,并把这些加载`main.ts`中。
在`systemjs.config.js`中已经将此文件配置为应用的入口,所以它已被浏览器所加载。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/main.ts', 'bootstrap')
:marked
The arguments used here are the root element of the application (which is
the same element we had `ng-app` on earlier), and the Angular 1.x modules
that we want to load. Since we're bootstrapping the app through
an `UpgradeModule`, we're actually now running the app as a hybrid Angular 1+2
app.
这里使用的参数是应用的根元素(也就是以前我们放`ng-app`的元素)和我们准备加载的Angular 1.x模块。
由于我们是通过`UpgradeAdapter`引导应用的所以实际在运行的应用实际上是一个Angular 1+2的混合体。
This means we are now running both Angular 1 and 2 at the same time. That's pretty
exciting! We're not running any actual Angular 2 components yet though,
so let's do that next.
我们现在同时运行着Angular 1和Angular 2。漂亮不过我们还没有运行什么实际的Angular 2组件接下来我们就做这件事。
.l-sub-section
:marked
#### Why declare _angular_ as _angular.IAngularStatic_?
#### 为何要声明*angular*为*angular.IAngularStatic*
`@types/angular` is declared as a UMD module, and due to the way
<a href="https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#support-for-umd-module-definitions" target="_blank">UMD typings</a>
work, once you have an ES6 `import` statement in a file all UMD typed modules must also be
imported via `import` statements instead of being globally available.
`@types/angular`声明为UMD模块根据<a href="https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#support-for-umd-module-definitions" target="_blank">UMD类型</a>
的工作方式一旦你在文件中有一条ES6的`import`语句所有的UMD类型化的模型必须都通过`import`语句导入,
而是不是全局可用。
Angular 1 is currently loaded by a script tag in `index.html`, which means that the whole app
has access to it as a global and uses the same instance of the `angular` variable.
If we used `import * as angular from 'angular'` instead we would also need to overhaul how we
load every file in our Angular 1 app to use ES6 modules in order to ensure Angular 1 was being
loaded correctly.
Angular 1是日前是通过`index.html`中的script标签加载这意味着整个应用是作为一个全局变量进行访问的
使用同一个`angular`变量的实例。
但如果我们使用`import * as angular from 'angular'`我还需要彻底修改Angular 1应用中加载每个文件的方式
确保Angular 1应用被正确加载。
This is a considerable effort and it often isn't worth it, especially since we are in the
process of moving our our to Angular 2 already.
Instead we declare `angular` as `angular.IAngularStatic` to indicate it is a global variable
and still have full typing support.
这需要相当多的努力通常也不值得去做特别是我们的应用正在朝着Angular 2前进。
但如果我们声明`angular`为`angular.IAngularStatic`,指明它是一个全局变量,
仍然可以获得全面的类型支持。
:marked
### Upgrading the Phone service
### 升级`Phone`服务
The first piece we'll port over to Angular 2 is the `Phone` service, which
resides in `app/core/phone/phone.service.ts` and makes it possible for components
to load phone information from the server. Right now it's implemented with
ngResource and we're using it for two things:
我们要移植到Angular 2的第一块是`Phone`工厂(位于`app/js/core/phones.factory.ts`)
并且让它能帮助控制器从服务器上加载电话信息。目前,它是用`ngResource`实现的,我们用它做两件事:
* For loading the list of all phones into the phone list component
* 把所有电话的列表加载到电话列表组件中。
* For loading the details of a single phone into the phone detail component.
* 把一台电话的详情加载到电话详情组件中。
We can replace this implementation with an Angular 2 service class, while
keeping our controllers in Angular 1 land.
我们可以用Angular 2的服务类来替换这个实现而把控制器继续留在Angular 1的地盘上。
In the new version, we import the Angular 2 HTTP module and call its `Http` service instead of `ngResource`.
在这个新版本中我们导入了Angular 2的HTTP模块并且用它的`Http`服务替换掉`NgResource`。
Re-open the `app.module.ts` file, import and add `HttpModule` to the `imports` array of the `AppModule`:
再次打开`app.module.ts`文件,导入并把`HttpModule`添加到`AppModule`的`imports`数组中:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'httpmodule', 'app.module.ts')
:marked
Now we're ready to upgrade the Phone service itself. We replace the ngResource-based
service in `phone.service.ts` with a TypeScript class decorated as `@Injectable`:
现在,我们已经准备好了升级`Phones`服务本身。我们将为`phone.service.ts`文件中基于ngResource的服务加上`@Injectable`装饰器:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.ts', 'classdef', 'app/core/phone/phone.service.ts (skeleton)')(format='.')
:marked
The `@Injectable` decorator will attach some dependency injection metadata
to the class, letting Angular 2 know about its dependencies. As described
by our [Dependency Injection Guide](../guide/dependency-injection.html),
this is a marker decorator we need to use for classes that have no other
Angular 2 decorators but still need to have their dependencies injected.
`@Injectable`装饰器将把一些依赖注入相关的元数据附加到该类上让Angular 2知道它的依赖信息。
就像在[依赖注入指南](../guide/dependency-injection.html)中描述过的那样,
这是一个标记装饰器我们要把它用在那些没有其它Angular 2装饰器并且自己有依赖注入的类上。
In its constructor the class expects to get the `Http` service. It will
be injected to it and it is stored as a private field. The service is then
used in the two instance methods, one of which loads the list of all phones,
and the other the details of a particular phone:
在它的构造函数中,该类期待一个`Http`服务。`Http`服务将被注入进来并存入一个私有字段。
然后该服务在两个实例方法中被使用到,一个加载所有电话的列表,另一个加载一台指定电话的详情:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.ts', 'fullclass')
:marked
The methods now return Observables of type `PhoneData` and `PhoneData[]`. This is
a type we don't have yet, so let's add a simple interface for it:
该方法现在返回一个`Phone`类型或`Phone[]`类型的可观察对象(Observable)。
这是一个我们从未用过的类型,因此我们得为它新增一个简单的接口:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.ts', 'phonedata-interface', 'app/core/phone/phone.service.ts (interface)')(format='.')
:marked
`@angular/upgrade/static` has a `downgradeInjectable` method for the purpose of making
Angular 2 services available to Angular 1 code. Use it to plug in the `Phone` service:
`@angular/upgrade/static`有一个`downgradeInjectable`方法可以使Angular 2服务在Angular 1的代码中可用。
使用它来插入`Phone`服务:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.ts', 'downgrade-injectable', 'app/core/phone/phone.service.ts (downgrade)')(format='.')
:marked
Here's the full, final code for the service:
最终,该类的全部代码如下:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.ts', null, 'app/core/phone/phone.service.ts')
:marked
Notice that we're importing the `map` operator of the RxJS `Observable` separately.
We need to do this for all RxJS operators that we want to use, since Angular 2
does not load all of them by default.
注意我们单独导入了RxJS `Observable`中的`map`操作符。
我们需要对想用的所有RxJS操作符这么做因为Angular 2默认不会加载所有RxJS操作符。
The new `Phone` service has the same features as the original, `ngResource`-based service.
Because it's an Angular 2 service, we register it with the `NgModule` providers:
这个新的`Phone`服务具有和老的基于`ngResource`的服务相同的特性。
因为它是Angular 2服务我们通过`NgModule`的`providers`数组来注册它:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'phone', 'app.module.ts')
:marked
Now that we are loading `phone.service.ts` through an import that is resolved
by SystemJS, we should **remove the &lt;script&gt; tag** for the service from `index.html`.
This is something we'll do to all our components as we upgrade them. Simultaneously
with the Angular 1 to 2 upgrade we're also migrating our code from scripts to modules.
现在我们正在用SystemJS加载`phone.service.ts`,我们应该从`index.html`中**移除该服务的`<script>`标签**。
这也是我们在升级所有组件时将会做的事。在从Angular 1向2升级的同时我们也把代码从脚本移植为模块。
At this point we can switch our two components to use the new service
instead of the old one. We `$inject` it as the downgraded `phone` factory,
but it's really an instance of the `Phone` class and we can annotate its type
accordingly:
这时,我们可以把两个控制器从使用老的服务切换成使用新的。我们像降级过的`phones`工厂一样`$inject`它,
但它实际上是一个`Phones`类的实例,并且我们可以据此注解它的类型:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.component.ng1.ts', null, 'app/phone-list/phone-list.component.ts')
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-detail/phone-detail.component.ng1.ts', null, 'app/phone-detail/phone-detail.component.ts')
:marked
What we have here are two Angular 1 components using an Angular 2 service!
The components don't need to be aware of this, though the fact that the
service returns Observables and not Promises is a bit of a giveaway.
In any case, what we've achieved is a migration of a service to Angular 2
without having to yet migrate the components that use it.
这里的两个Angular 1控制器在使用Angular 2的服务控制器不需要关心这一点尽管实际上该服务返回的是可观察对象(Observable),而不是承诺(Promise)。
无论如何我们达到的效果都是把服务移植到Angular 2而不用被迫移植组件来使用它。
.alert.is-helpful
:marked
We could also use the `toPromise` method of `Observable` to turn those
Observables into Promises in the service. This can in many cases further
reduce the amount of changes needed in the component controllers.
我们也能使用`Observable`的`toPromise`方法来在服务中把这些可观察对象转变成承诺,以进一步减小组件控制器中需要修改的代码量。
:marked
### Upgrading Components
### 升级组件
Next, let's upgrade our Angular 1 components to Angular 2 components. We'll
do it one at a time, while still keeping the application in hybrid mode.
As we make these conversions, we'll also be defining our first Angular 2 *pipes*.
接下来我们把Angular 1的控制器升级成Angular 2的组件。我们每次升级一个同时仍然保持应用运行在混合模式下。
在做转换的同时我们还将自定义首个Angular 2*管道*。
Let's look at the phone list component first. Right now it contains a TypeScript
controller class and a component definition object. We can morph this into
an Angular 2 component by just renaming the controller class and turning the
Angular 1 component definition object into an Angular 2 `@Component` decorator.
We can then also remove the static `$inject` property from the class:
让我们先看看电话列表组件。它目前包含一个TypeScript控制器类和一个组件定义对象。重命名控制器类
并把Angular 1的组件定义对象更换为Angular 2 `@Component`装饰器这样我们就把它变形为Angular 2
的组件了。然后,我们还从类中移除静态`$inject`属性。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.component.ts', 'initialclass', 'app/phone-list/phone-list.component.ts')
:marked
The `selector` attribute is a CSS selector that defines where on the page the component
should go. In Angular 1 we do matching based on component names, but in Angular 2 we
have these explicit selectors. This one will match elements with the name `phone-list`,
just like the Angular 1 version did.
`selector`属性是一个CSS选择器用来定义组件应该被放在页面的哪。在Angular 1我们基于组件名字来匹配
但是在Angular 2中我们要有一个专门指定的选择器。本组件将会对应元素名字`phone-list`和Angular 1版本一样。
We now also need to convert the template of this component into Angular 2 syntax.
The search controls replace the Angular 1 `$ctrl` expressions
with Angular 2's two-way `[(ngModel)]` binding syntax:
现在我们还需要将组件的模版也转换为Angular 2语法。在搜索控件中我们要为把Angular 1的`$ctrl`表达式替换成Angular 2的双向绑定语法`[(ngModel)]`
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.template.html', 'controls', 'app/phone-list/phone-list.template.html (search controls)')(format='.')
:marked
Replace the list's `ng-repeat` with an `*ngFor` as
[described in the Template Syntax page](../guide/template-syntax.html#directives).
Replace the image tag's `ng-src` with a binding to the native `src` property.
我们需要把列表中的`ng-repeat`替换为`*ngFor`以及它的`let var of iterable`语法,
该语法在[模板语法指南中讲过](../guide/template-syntax.html#directives)。
对于图片,我们可以把`img`标签的`ng-src`替换为一个标准的`src`属性(property)绑定。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.template.html', 'list', 'app/phone-list/phone-list.template.html (phones)')(format='.')
:marked
#### No Angular 2 _filter_ or _orderBy_ filters
#### Angular 2中没有`filter`或`orderBy`过滤器
The built-in Angular 1 `filter` and `orderBy` filters do not exist in Angular 2,
so we need to do the filtering and sorting ourselves.
Angular 2中并不存在Angular 1中内置的`filter`和`orderBy`过滤器。
所以我们得自己实现进行过滤和排序。
We replaced the `filter` and `orderBy` filters with bindings to the `getPhones()` controller method,
which implements the filtering and ordering logic inside the component itself.
我们把`filter`和`orderBy`过滤器改成绑定到控制器中的`getPhones()`方法,通过该方法,组件本身实现了过滤和排序逻辑。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.component.ts', 'getphones', 'app/phone-list/phone-list.component.ts')
:marked
Now we need to downgrade our Angular 2 component so we can use it in Angular 1.
Instead of registering a component, we register a `phoneList` *directive*,
a downgraded version of the Angular 2 component.
现在我们需要降级我们的Angular 2组件这样我们就可以在Angular 1中使用它。
我们需要注册一个`phoneList`*指令*而不是注册一个组件它是一个降级版的Angular 2组件。
The `as angular.IDirectiveFactory` cast tells the TypeScript compiler
that the return value of the `downgradeComponent` method is a directive factory.
强制类型转换`as angular.IDirectiveFactory`告诉TypeScript编译器`downgradeComponent`方法
的返回值是一个指令工厂。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.component.ts', 'downgrade-component', 'app/phone-list/phone-list.component.ts')
:marked
The new `PhoneListComponent` uses the Angular 2 `ngModel` directive, located in the `FormsModule`.
Add the `FormsModule` to `NgModule` imports, declare the new `PhoneListComponent` and
finally add it to `entryComponents` since we downgraded it:
新的`PhoneListComponent`使用Angular 2的`ngModel`指令,它位于`FormsModule`中。
把`FormsModule`添加到`NgModule`的`imports`中,并声明新的`PhoneListComponent`组件,
最后由我们把它降级了,添加到`entryComponents`
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'phonelist', 'app.module.ts')
:marked
Remove the &lt;script&gt; tag for the phone list component from `index.html`.
从`index.html`中移除电话列表组件的&lt;script&gt;标签。
Now set the remaining `phone-detail.component.ts` as follows:
现在,剩下的`phone-detail.component.ts`文件变成了这样:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-detail/phone-detail.component.ts', null, 'app/phone-detail/phone-detail.component.ts')
:marked
This is similar to the phone list component.
The new wrinkle is the `@Inject` decorator that identifies the `$routeParams` dependency.
这和电话列表组件很相似。
这里的窍门在于`@Inject`装饰器,它标记出了`$routeParams`依赖。
The Angular 1 injector has an Angular 1 router dependency called `$routeParams`.
which was injected into `PhoneDetails` when it was still an Angular 1 controller.
We intend to inject it into the new `PhoneDetailsComponent`.
Angular 1注入器具有Angular 1路由器的依赖叫做`$routeParams`。
它被注入到了`PhoneDetails`中,但`PhoneDetails`现在还是一个Angular 1控制器。
我们应该把它注入到新的`PhoneDetailsComponent`中。
Unfortunately, Angular 1 dependencies are not automatically available to Angular 2 components.
We must use a [Factory provider](#making-angular-1-dependencies-injectable-to-angular-2)
to make `$routeParams` an Angular 2 provider.
Do that in `app.module.ts`:
不幸的是Angular 1的依赖不会自动在Angular 2的组件中可用。
我们必须使用[工厂提供商factory provider](#making-angular-1-dependencies-injectable-to-angular-2)
来把`$routeParams`包装成Angular 2的服务提供商。
在`app.module.ts`中这样写:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'routeparams', 'app/app.module.ts ($routeParms)')(format='.')
:marked
Convert the phone detail component template into Angular 2 syntax as follows:
我们现在也要把该组件的模板转变成Angular 2的语法。
这里是它完整的新模板:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-detail/phone-detail.template.html', null, 'app/phone-detail/phone-detail.template.html')
:marked
There are several notable changes here:
这里有几个值得注意的改动:
* We've removed the `$ctrl.` prefix from all expressions.
* 我们从所有表达式中移除了`$ctrl.`前缀。
* Just like we did in the phone list, we've replaced `ng-src` with property
bindings for the standard `src` property.
* 正如我们在电话列表中做过的那样,我们把`ng-src`替换成了标准的`src`属性绑定。
* We're using the property binding syntax around `ng-class`. Though Angular 2
does have [a very similar `ngClass`](../guide/template-syntax.html#directives)
as Angular 1 does, its value is not magically evaluated as an expression.
In Angular 2 we always specify in the template when an attribute's value is
a property expression, as opposed to a literal string.
* 我们在`ng-class`周围使用了属性绑定语法。虽然Angular 2中有一个
和Angular 1中[非常相似的`ngClass`](../guide/template-syntax.html#directives)指令,
但是它的值不会神奇的作为表达式进行计算。在Angular 2中模板中的属性(Attribute)值总是被作为
属性(Property)表达式计算,而不是作为字符串字面量。
* We've replaced `ng-repeat`s with `*ngFor`s.
* 我们把`ng-repeat`替换成了`*ngFor`。
* We've replaced `ng-click` with an event binding for the standard `click`.
* 我们把`ng-click`替换成了一个到标准`click`事件的绑定。
* We've wrapped the whole template in an `ngIf` that causes it only to be
rendered when there is a phone present. We need this because when the component
first loads, we don't have `phone` yet and the expressions will refer to a
non-existing value. Unlike in Angular 1, Angular 2 expressions do not fail silently
when we try to refer to properties on undefined objects. We need to be explicit
about cases where this is expected.
* 我们把整个模板都包裹进了一个`ngIf`中,这导致只有当存在一个电话时它才会渲染。我们必须这么做,
是因为组件首次加载时我们还没有`phone`变量,这些表达式就会引用到一个不存在的值。
和Angular 1不同当我们尝试引用未定义对象上的属性时Angular 2中的表达式不会默默失败。
我们必须明确指出这种情况是我们所期望的。
Add `PhoneDetailComponent` component to the `NgModule` _declarations_ and _entryComponents_:
把`PhoneDetailComponent`组件添加到`NgModule`的_declarations_和_entryComponents_中
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'phonedetail', 'app.module.ts')
:marked
We should now also remove the phone detail component &lt;script&gt; tag from `index.html`.
我们现在应该从`index.html`中移除电话详情组件的&lt;script>。
#### Add the _CheckmarkPipe_
#### 添加*CheckmarkPipe*
The Angular 1 directive had a `checkmark` _filter_.
Let's turn that into an Angular 2 **pipe**.
Angular 1指令中有一个`checkmark`*过滤器*我们把它转换成Angular 2的**管道**。
There is no upgrade method to convert filters into pipes.
You won't miss it.
It's easy to turn the filter function into an equivalent Pipe class.
The implementation is the same as before, repackaged in the `transform` method.
Rename the file to `checkmark.pipe.ts` to conform with Angular 2 conventions:
没有什么升级方法能把过滤器转换成管道。
但我们也并不需要它。
把过滤器函数转换成等价的Pipe类非常简单。
实现方式和以前一样,但把它们包装进`transform`方法中就可以了。
把该文件改名成`checkmark.pipe.ts`以符合Angular 2中的命名约定
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/checkmark/checkmark.pipe.ts', null, 'app/core/checkmark/checkmark.pipe.ts')(format='.')
:marked
Now import and declare the newly created pipe and
remove the filter &lt;script&gt; tag from `index.html`:
当我们做这个修改时,也要同时从`core`模块文件中移除对该过滤器的注册。该模块的内容变成了:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/app.module.ts', 'checkmarkpipe', 'app.module.ts')
:marked
### Switching To The Angular 2 Router And Bootstrap
### 切换到Angular 2路由器和引导程序
At this point we've replaced all Angular 1 application components with
their Angular 2 counterparts.
此刻我们已经把所有Angular 1程序中的部件替换成了Angular 2中的等价物。
The application is still bootstrapped as a hybrid app.
There's no need for that anymore.
该应用仍然使用混合式应用的方式进行引导,但其实已经不需要了。
It's time to remove the last remnants of Angular 1 in two final steps:
在最后两步中我们彻底移除Angular 1的残余势力
1. Switch to the Angular 2 router.
1. 切换到Angular 2路由器。
1. Bootstrap as a pure Angular 2 app.
1. 作为纯Angular 2应用进行引导。
#### Switch to the Angular 2 router
#### 切换到Angular 2路由器
Angular 2 has an [all-new router](router.html).
Angular 2有一个[全新的路由器](router.html)。
Like all routers, it needs a place in the UI to display routed views.
The Angular 2 that's the `<router-outlet>` and it belongs in a *root component*
at the top of the applications component tree.
像所有的路由器一样它需要在UI中指定一个位置来显示路由的视图。
在Angular 2中它是`<router-outlet>`,并位于应用组件树顶部的*根组件*中。
We don't yet have such a root component, because the app is still managed as an Angular 1 app.
Create a new `app.component.ts` file with the following `AppComponent` class:
我们还没有这样一个根组件因为该应用仍然是像一个Angular 1应用那样被管理的。
创建新的`app.component.ts`文件,放入像这样的`AppComponent`类:
+makeExample('upgrade-phonecat-3-final/ts/app/app.component.ts', null, 'app/app.component.ts')(format='.')
:marked
It has a simple template that only includes the `<router-outlet>`.
This component just renders the contents of the active route and nothing else.
它有一个很简单的模板,只包含`<router-outlet>`。
该组件只负责渲染活动路由的内容,此外啥也不干。
The selector tells Angular 2 to plug this root component into the `<phonecat-app>`
element on the host web page when the application launches.
该选择器告诉Angular 2当应用启动时就把这个根组件插入到宿主页面的`<phonecat-app>`元素中。
Add this `<phonecat-app>` element to the `index.html`.
It replaces the old Angular 1 `ng-view` directive:
把这个`<phonecat-app>`元素插入到`index.html`中。
用它来代替Angular 1中的`ng-view`指令:
+makeExample('upgrade-phonecat-3-final/ts/index.html', 'appcomponent', 'index.html (body)')(format='.')
:marked
#### Create the _Routing Module_
#### 创建*路由模块*
A router needs configuration whether it's the Angular 1 or Angular 2 or any other router.
无论在Angular 1还是Angular 2或其它框架中路由器都需要进行配置。
The details of Angular 2 router configuration are best left to the [Routing documentation](router.html)
which recommends that you create a `NgModule` dedicated to router configuration
(called a _Routing Module_):
Angular 2路由器配置的详情最好去查阅下[路由与导航](router.html)文档。
它建议你创建一个专们用于路由器配置的`NgModule`(名叫*路由模块*)。
+makeExample('upgrade-phonecat-3-final/ts/app/app-routing.module.ts', null, 'app/app-routing.module.ts')
:marked
This module defines a `routes` object with two routes to the two phone components
and a default route for the empty path.
It passes the `routes` to the `RouterModule.forRoot` method which does the rest.
该模块定义了一个`routes`对象,它带有两个路由,分别指向两个电话组件,以及为空路径指定的默认路由。
它把`routes`传给`RouterModule.forRoot`方法,该方法会完成剩下的事。
A couple of extra providers enable routing with "hash" URLs such as `#!/phones` instead of the default "push state" strategy.
一些额外的提供商让路由器使用“hash”策略解析URL比如`#!/phones`而不是默认的“Push State”策略。
Now update the `AppModule` to import this `AppRoutingModule` and also the
declare the root `AppComponent`:
现在,修改`AppModule`,让它导入这个`AppRoutingModule`,并同时声明根组件`AppComponent`
+makeExample('upgrade-phonecat-3-final/ts/app/app.module.ts', null, 'app/app.module.ts')
:marked
The Angular 2 router passes route parameters differently.
Correct the `PhoneDetail` component constructor to expect an injected `ActivatedRoute` object.
Extract the `phoneId` from the `ActivatedRoute.snapshot.params` and fetch the phone data as before:
Angular 2路由器传递路由参数的方式不同。
修改`PhoneDetail`组件的构造函数,来取得一个注入的`ActivatedRoute`对象。
从`ActivatedRoute.snapshot.params`中提取`phoneId`,并像以前那样获取电话数据:
+makeExample('upgrade-phonecat-3-final/ts/app/phone-detail/phone-detail.component.ts', null, 'app/phone-detail/phone-detail.component.ts')
:marked
#### Generate links for each phone
#### 为每个电话生成链接
We no longer have to hardcode the links to phone details in the phone list.
We can generate them data binding each phone's `id` to the `routerLink` directive
and let that directive construct the appropriate URL to the `PhoneDetailComponent`:
在电话列表中,我们不用再被迫硬编码电话详情的链接了。
我们可以通过把每个电话的`id`绑定到`routerLink`指令来生成它们了,该指令的构造函数会为`PhoneDetailComponent`生成正确的URL
+makeExample('upgrade-phonecat-3-final/ts/app/phone-list/phone-list.template.html', 'list', 'app/phone-list/phone-list.template.html (list with links)')(format='.')
.l-sub-section
:marked
See the [Routing](router.html) page for details.
要了解详情,请查看[路由与导航](router.html)页。
:marked
#### Bootstrap as an Angular 2 app
#### 作为Angular 2应用进行引导
You may have noticed one extra `bootstrap` metadata property added to the `AppModule`
你可能注意到了,有一个额外的元数据属性`bootstrap`添加进了`AppModule`中。
+makeExample('upgrade-phonecat-3-final/ts/app/app.module.ts', 'bootstrap', 'app/app.module.ts (bootstrap)')(format='.')
:marked
That tells Angular 2 that it should bootstrap the app with the _root_ `AppComponent` and
insert it's view into the host web page.
这是在告诉Angular 2它应该使用根组件`AppComponent`来引导该应用并且把它的视图插入宿主页面中。
Now switch the bootstrap method of the application from the `UpgradeAdapter`
to the Angular 2 way.
现在,把该应用的引导方法从`UpgradeAdapter`的切换到Angular 2的方式。
Now we can drop `upgrade.bootstrap` from our application bootstrap, and remove the
`ngDoBootstrap()` override from `app.module.ts`
现在我可以从应用启动部分删除`upgrade.bootstrap`,从`app.module.ts`中删除
`ngDoBootstrap()`覆盖函数:
+makeExample('upgrade-phonecat-3-final/ts/app/main.ts', null, 'main.ts')
+makeExample('upgrade-phonecat-3-final/ts/app/app.module.ts', null, 'app.module.ts')
:marked
You are now running a pure Angular 2 application!
我们现在运行的就是纯正的Angular 2应用了
### Say Goodbye to Angular 1
### 再见Angular 1
It is time to take off the training wheels and let our application begin
its new life as a pure, shiny Angular 2 app. The remaining tasks all have to
do with removing code - which of course is every programmer's favorite task!
是时候把辅助训练的轮子摘下来了让我们的应用作为一个纯粹、闪亮的Angular 2程序开始它的新生命吧。
剩下的所有任务就是移除代码 —— 这当然是每个程序员最喜欢的任务!
If you haven't already, remove all references to the `UpgradeModule` from `app.module.ts`,
as well as any [Factory provider](#making-angular-1-dependencies-injectable-to-angular-2) for Angular 1 services.
Also remove any `downgradeComponent()` you find, together with the associated Angular 1
directive declarations.
如果你还没有这么做,请从`app.module.ts删除所有`UpgradeModule的引用
以及所有用于Angular 1服务的[工厂供应商factory provider](#making-angular-1-dependencies-injectable-to-angular-2)。
还有删除所有的`downgradeComponent()`以及与Angular 1相关的指令声明。
:marked
You may also completely remove the following files. They are Angular 1
module configuration files and not needed in Angular 2:
我们还要完全移除了下列文件。它们是Angular 1的模块配置文件和类型定义文件在Angular 2中不需要了
* `app/app.module.ng1.ts`
* `app/app.config.ts`
* `app/core/core.module.ts`
* `app/core/phone/phone.module.ts`
* `app/phone-detail/phone-detail.module.ts`
* `app/phone-list/phone-list.module.ts`
The external typings for Angular 1 may be uninstalled as well. The only ones
we still need are for Jasmine and Angular 2 polyfills.
Angular 1的外部类型定义文件还需要被反安装。我们现在只需要Jasmine的那些。
code-example(format="").
npm uninstall @types/angular @types/angular-animate @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev
:marked
Finally, from `index.html`, remove all references to
Angular 1 scripts, the Angular 2 upgrade module, and jQuery. When we're done,
this is what it should look like:
最后,从`index.html`和`karma.conf.js`中移除所有到Angular 1脚本的引用比如jQuery。
当这些全部做完时,`index.html`看起来应该是这样的:
+makeExample('upgrade-phonecat-3-final/ts/index.html', 'full', 'index.html')
:marked
That is the last we'll see of Angular 1! It has served us well but now
it's time to say goodbye.
这是我们最后一次看到Angular 1了它曾经带给我们很多帮助不过现在是时候说再见了。
.l-main-section
:marked
## Appendix: Upgrading PhoneCat Tests
## 附录升级PhoneCat的测试
Tests can not only be retained through an upgrade process, but they can also be
used as a valuable safety measure when ensuring that the application does not
break during the upgrade. E2E tests are especially useful for this purpose.
测试不仅要在升级过程中被保留,它还是确保应用在升级过程中不会被破坏的一个安全指示器。
要达到这个目的E2E测试尤其有用。
### E2E Tests
### E2E测试
The PhoneCat project has both E2E Protractor tests and some Karma unit tests in it.
Of these two, E2E tests can be dealt with much more easily: By definition,
E2E tests access our application from the *outside* by interacting with
the various UI elements the app puts on the screen. E2E tests aren't really that
concerned with the internal structure of the application components. That
also means that although we modify our project quite a bit during the upgrade, the E2E
test suite should keep passing with just minor modifications. This is because
we don't change how the application behaves from the user's point of view.
PhoneCat项目中同时有基于Protractor的E2E测试和一些基于Karma的单元测试。
对这两者来说E2E测试的转换要容易得多根据定义E2E测试通过与应用中显示的这些UI元素互动从*外部*访问我们的应用来进行测试。
E2E测试实际上并不关心这些应用中各部件的内部结构。这也意味着虽然我们已经修改了此应用程序
但是E2E测试套件仍然应该能像以前一样全部通过。因为从用户的角度来说我们并没有改变应用的行为。
During TypeScript conversion, there is nothing we have to do to keep E2E tests
working. It is only when we change our bootstrap to that of an Hybrid app that we need to
make some changes.
在转成TypeScript期间我们不用做什么就能让E2E测试正常工作。
只有当我们想做些修改而把组件及其模板升级到Angular 2时才需要做些处理。
The following change is needed in `protractor-conf.js` to sync with hybrid apps:
需要对`protractor-conf.js`做如修改,与混合应用同步:
code-example(format="").
ng12Hybrid: true
:marked
The next set of changes is when we start to upgrade components and their template to Angular 2.
This is because the E2E tests have matchers that are specific to Angular 1.
For PhoneCat we need to make the following changes in order to make things work with Angular 2:
当我们开始组件和模块升级到Angular 2时还需要一系列后续的修改。
这是因为E2E测试有一些匹配器是Angular 1中特有的。对于PhoneCat来说为了让它能在Angular 2下工作我们得做下列修改
table
tr
th
p Previous code
p 老代码
th
p New code
p 新代码
th
p Notes
p 说明
tr
td
:marked
`by.repeater('phone in $ctrl.phones').column('phone.name')`
td
:marked
`by.css('.phones .name')`
td
:marked
The repeater matcher relies on Angular 1 `ng-repeat`
repeater匹配器依赖于Angular 1中的`ng-repeat`
tr
td
:marked
`by.repeater('phone in $ctrl.phones')`
td
:marked
`by.css('.phones li')`
td
:marked
The repeater matcher relies on Angular 1 `ng-repeat`
repeater匹配器依赖于Angular 1中的`ng-repeat`
tr
td
:marked
`by.model('$ctrl.query')`
td
:marked
`by.css('input')`
td
:marked
The model matcher relies on Angular 1 `ng-model`
model匹配器依赖于Angular 1中的`ng-model`
tr
td
:marked
`by.model('$ctrl.orderProp')`
td
:marked
`by.css('select')`
td
:marked
The model matcher relies on Angular 1 `ng-model`
model匹配器依赖于Angular 1中的`ng-model`
tr
td
:marked
`by.binding('$ctrl.phone.name')`
td
:marked
`by.css('h1')`
td
:marked
The binding matcher relies on Angular 1 data binding
binding匹配器依赖于Angular 1的数据绑定
:marked
When the bootstrap method is switched from that of `UpgradeModule` to
pure Angular 2, Angular 1 ceases to exist on the page completely.
At this point we need to tell Protractor that it should not be looking for
an Angular 1 app anymore, but instead it should find *Angular 2 apps* from
the page.
当引导方式从`UpgradeModule`切换到纯Angular 2的时Angular 1就从页面中完全消失了。
此时我们需要告诉Protractor它不用再找Angular 1应用了而是从页面中查找*Angular 2*应用。
于是在`protractor-conf.js`中做下列修改:
Replace the `ng12Hybrid` previously added with the following in `protractor-conf.js`:
替换之前在`protractor-conf.js`中加入 `ng12Hybrid`,象这样:
code-example(format="").
useAllAngular2AppRoots: true,
:marked
Also, there are a couple of Protractor API calls in the PhoneCat test code that
are using the Angular 1 `$location` service under the hood. As that
service is no longer there after the upgrade, we need to replace those calls with ones
that use WebDriver's generic URL APIs instead. The first of these is
the redirection spec:
同样我们的测试代码中有两个Protractor API调用内部使用了`$location`。该服务没有了,
我们就得把这些调用用一个WebDriver的通用URL API代替。第一个API是“重定向(redirect)”规约:
+makeExample('upgrade-phonecat-3-final/e2e-spec.ts', 'redirect', 'e2e-tests/scenarios.ts')
:marked
And the second is the phone links spec:
然后是“电话链接(phone links)”规约:
+makeExample('upgrade-phonecat-3-final/e2e-spec.ts', 'links', 'e2e-tests/scenarios.ts')
:marked
### Unit Tests
### 单元测试
For unit tests, on the other hand, more conversion work is needed. Effectively
they need to be *upgraded* along with the production code.
另一方面,对于单元测试来说,需要更多的转化工作。实际上,它们需要随着产品代码一起升级。
During TypeScript conversion no changes are strictly necessary. But it may be
a good idea to convert the unit test code into TypeScript as well, as the same
benefits we from TypeScript in production code also applies to tests.
在转成TypeScript期间严格来讲没有什么改动是必须的。但把单元测试代码转成TypeScript仍然是个好主意
产品代码从TypeScript中获得的那些增益也同样适用于测试代码。
For instance, in the phone detail component spec we can use not only ES2015
features like arrow functions and block-scoped variables, but also type
definitions for some of the Angular 1 services we're consuming:
比如在这个电话详情组件的规约中我们不仅用到了ES2015中的箭头函数和块作用域变量这些特性还为所用的一些
Angular 1服务提供了类型定义。
+makeExample('upgrade-phonecat-1-typescript/ts/app/phone-detail/phone-detail.component.spec.ts', null, 'app/phone-detail/phone-detail.component.spec.ts')
:marked
Once we start the upgrade process and bring in SystemJS, configuration changes
are needed for Karma. We need to let SystemJS load all the new Angular 2 code,
which can be done with the following kind of shim file:
一旦我们开始了升级过程并引入了SystemJS还需要对Karma进行配置修改。
我们需要让SystemJS加载所有的Angular 2新代码
+makeExample('upgrade-phonecat-2-hybrid/ts/karma-test-shim.1.js', null, 'karma-test-shim.js')
:marked
The shim first loads the SystemJS configuration, then Angular 2's test support libraries,
and then the application's spec files themselves.
这个shim文件首先加载了SystemJS的配置然后是Angular 2的测试支持库然后是应用本身的规约文件。
Karma configuration should then be changed so that it uses the application root dir
as the base directory, instead of `app`.
然后需要修改Karma配置来让它使用本应用的根目录作为基础目录(base directory),而不是`app`。
+makeExample('upgrade-phonecat-2-hybrid/ts/karma.conf.ng1.js', 'basepath', 'karma.conf.js')
:marked
Once this is done, we can load SystemJS and other dependencies, and also switch the configuration
for loading application files so that they are *not* included to the page by Karma. We'll let
the shim and SystemJS load them.
一旦这些完成了我们就能加载SystemJS和其它依赖并切换配置文件来加载那些应用文件而*不用*在Karma页面中包含它们。
我们要让这个shim文件和SystemJS去加载它们。
+makeExample('upgrade-phonecat-2-hybrid/ts/karma.conf.ng1.js', 'files', 'karma.conf.js')
:marked
Since the HTML templates of Angular 2 components will be loaded as well, we need to help
Karma out a bit so that it can route them to the right paths:
由于Angular 2组件中的HTML模板也同样要被加载所以我们得帮Karma一把帮它在正确的路径下找到这些模板
+makeExample('upgrade-phonecat-2-hybrid/ts/karma.conf.ng1.js', 'html', 'karma.conf.js')
:marked
The unit test files themselves also need to be switched to Angular 2 when their production
counterparts are switched. The specs for the checkmark pipe are probably the most straightforward,
as the pipe has no dependencies:
如果产品代码被切换到了Angular 2单元测试文件本身也需要切换过来。对勾(checkmark)管道的规约可能是最简单的,因为它没有任何依赖:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/checkmark/checkmark.pipe.spec.ts', null, 'app/core/checkmark/checkmark.pipe.spec.ts')
:marked
The unit test for the phone service is a bit more involved. We need to switch from the mocked-out
Angular 1 `$httpBackend` to a mocked-out Angular 2 Http backend.
`Phone`服务的测试会牵扯到一点别的。我们需要把模拟版的Angular 1 `$httpBackend`服务切换到模拟板的Angular 2 Http后端。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.spec.ts', null, 'app/core/phone/phone.service.spec.ts')
:marked
For the component specs we can mock out the `Phone` service itself, and have it provide
canned phone data. We use Angular's component unit testing APIs for both components.
对于组件的规约,我们可以模拟出`Phone`服务本身并且让它提供电话的数据。我们可以对这些组件使用Angular的组件单元测试API。
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-detail/phone-detail.component.spec.ts', null, 'app/phone-detail/phone-detail.component.spec.ts')
+makeExample('upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.component.spec.ts', null, 'app/phone-list/phone-list.component.spec.ts')
:marked
Finally, we need to revisit both of the component tests when we switch to the Angular 2
router. For the details component we need to provide a mock of Angular 2 `ActivatedRoute` object
instead of using the Angular 1 `$routeParams`.
最后当我们切换到Angular 2路由时我们需要重新过一遍这些组件测试。对详情组件来说我们需要提供一个Angular 2
`RouteParams`的mock对象而不再用Angular 1中的`$routeParams`。
+makeExample('upgrade-phonecat-3-final/ts/app/phone-detail/phone-detail.component.spec.ts', 'activatedroute', 'app/phone-detail/phone-detail.component.spec.ts')
:marked
And for the phone list component we need to set up a few things for the router itself so that
the route link directive will work.
对于电话列表组件来说,我们需要为路由器本身略作设置,以便它的路由链接(`routerLink`)指令能够正常工作。
+makeExample('upgrade-phonecat-3-final/ts/app/phone-list/phone-list.component.spec.ts', 'routestuff', 'app/phone-list/phone-list.component.spec.ts')