Home > Web Front-end > JS Tutorial > body text

The magic of Angular 5.0

php中世界最好的语言
Release: 2017-11-18 16:06:15
Original
2039 people have browsed it

No, no, no, do you know Angular? While many people are not very familiar with Angular1, Angular5 has come out. Today I will give you a good introduction to Angular5. What changes have been made in previous versions?

Build Optimizer

Starting in 5.0.0, product builds executed via the CLI use the build optimizer by default.

The build optimizer is a tool in the CLI that can make the built package smaller based on our understanding of your Angular application.

Building an optimizer has two main tasks. First, mark certain parts of your application as pure so that existing tools can use it to improve the optimization effect of "tree shaking" and remove unnecessary things from the application.

Secondly, the build optimizer will remove Angular decorator code from your app. Decorators are only used by the compiler and are not used during runtime and can be deleted. Both of the above optimizations can reduce the size of the generated JS package and speed up application startup.

Angular Universal state transfer API and support for DOM

This makes it easier to share application state between the server and the client.

Angular Universal is a project that helps developers perform server-side rendering (SSR). The HTML generated by server-side rendering is friendly to spiders and crawlers that do not support JS, and helps improve user-perceived performance.

In 5.0.0, the development team added ServerTransferStateModule and the corresponding BrowserTransferStateModule. This module can help developers add relevant information to the content generated by server-side rendering and then send it to the client to avoid repeated generation. This is useful for scenarios where data is retrieved via HTTP. By transferring status from the server to the client, the developer does not have to make a second HTTP request. Documentation for the status transfer will be released in a few weeks.

The Angular Universal team also added the platform server Domino to the platform server. Domino supports more out-of-the-box DOM operations in a server-side environment, which can improve our support for non-server-side third-party JS and component libraries.

Compiler improvements

To support incremental compilation, we have improved the Angular compiler. As a result, rebuilding is accelerated, especially for product builds and AOT builds, and the effect is more obvious. We also enhanced the decorator to reduce package size by removing whitespace.

TypeScript conversion

Now, the underlying working mechanism of the Angular compiler is TypeScript conversion, making incremental rebuilds much faster. TypeScript conversion is a new feature of TypeScript 2.3 that allows us to dive into the standard TypeScript compilation pipeline.

With the AOT tag open, you can use the above mechanism by running ng serve.

ng serve --aot

I suggest everyone give it a try. This configuration will become the default for the CLI in the future. Many projects have performance issues involving thousands of components, and we hope projects of all sizes can benefit from these improvements.

When performing an incremental AOT build of https://angular.io, the new compiler pipeline can save 95% of the build time (test results on our development machine are from more than 40 seconds reduced to less than 2 seconds).

Our goal is to make AOT compilation fast enough for developers to use it for development. Now, we have broken into under 2 seconds, so AOT may be enabled by default in future CLIs.

As a transition step to this conversion, we no longer need genDir, and outDir has also changed: now, we will type all the files generated for the package into node_modules.

Keep whitespace

In the past the compiler would faithfully reproduce and include tabs, newlines, and whitespace in templates. You can now choose whether to include whitespace in components and applications.

This configuration can be specified in the decorator of each component, and the current default value is true.

@Component({
  templateUrl: 'about.component.html',
  preserveWhitespaces: false
}
export class AboutComponent {}
Copy after login

Or you can configure it globally in tsconfig.json, where the default value is also true.

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": []
  },
  "angularCompilerOptions": {
    "preserveWhitespaces": false
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
Copy after login

The general rule is that component-level configuration should override application-level configuration. The development team plans to change the default value to false in the future to save space for developers by default. Don't worry about your

 tags, the compiler will handle them intelligently. </p><p>Improved decorator support</p><p>Now supports <a href="http://www.php.cn/wiki/81.html" target="_blank">expression </a>lowering (expression lowering) in Lambda and object literal useValue, useFactory and data decorators. This makes it possible to use values ​​that can only be lowered in decorators that can be evaluated at runtime. </p><p>So now you can use Lambda functions instead of named functions. In other words, executing the code will not affect your d.ts or your external API. </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false">Component({
  provider: [{provide: SOME_TOKEN, useFactory: () => null}]
})
export class MyClass {}
Copy after login

We also degrade the expression as part of useValue.

Component({

provider: [{provide: SOME_TOKEN, useValue: SomeEnum.OK}]

})

export class MyClass {}

Internationalized numerical, date and currency pipes

We have written new numerical, date and currency pipes to make cross-browser internationalization more convenient, without the need to use i18n putty scripts ( polyfill).

在以前版本的Angular中,我们一直依赖浏览器及其i18n API提供数值、日期和货币格式。为此,很多开发者都在使用腻子脚本(polyfill),而结果也不好。很多人反馈说一些常见的格式(如货币)不能做到开箱即用。

而在5.0.0中,我们把这个管道更新成了自己的实现,依赖CLDR提供广泛的地区支持,而且可配置。以下是我们对v4和v5所做的比较:a document comparing the pipe behavior between v4 and v5。

如果你还没条件使用新管理,可以导入DeprecatedI18NPipesModule以降级到旧的行为。

StaticInjector代替ReflectiveInjector

为了消除对更多腻子脚本(polyfill)的依赖,我们用StaticInjector代替了ReflectiveInjector。前者不再需要Reflect,为开发者减少了应用大小。

以前

ReflectiveInjector.resolveAndCreate(providers);

以后

Injector.create(providers);

提升Zone的速度

一方面提升了Zone的速度,另一方面也可以在特别关注性能的应用中绕过它。

若要绕过它,启动应用时加上noop:

platformBrowserDynamic().bootstrapModule(AppModule, {ngZone: 'noop'}).then( ref => {} );

这里有一个完整的例子:the example ng-component-state project。

exportAs

组件和指令中增加了对多名称的支持。这有助于用户实现无痛迁移。通过把指令导出为多个名称,可以在不破坏原有代码的情况下在Angular语法中使用新名称。Angular Material项目已经在其前缀迁移项目中用上了,对其他组件作者肯定也有用。

示例

@Component({
  moduleId: module.id,
  selector: &#39;a[mat-button], a[mat-raised-button], a[mat-icon-button], a[mat-fab], a[mat-mini-fab]&#39;,
  exportAs: &#39;matButton, matAnchor&#39;,
  .
  .
  .
}
Copy after login

HttpClient

v4.3在@angular/common中推出过HttpClient,用于在Angular中发送请求,它小巧易用。HttpClient受到了开发者的广泛赞誉,因此我们推荐在所有应用中使用它,放弃之前的@angular/http library。

要升级HttpClient,需要在每个模块的@angular/common/http中把HttpModule替换为HttpClientModule,注入HttpClient服务,删除所有map(res => res.json())。

CLI v1.5

从Angluar CLI v1.5开始,已经开始支持Angluar v5.0.0,默认生成v5项目。

在这次小版本升级中,我们默认打开了构建优化器,让开发者拿到更小的包。

我们还修改了使用.tsconfig文件的方式,以更严格地遵守TypeScript标准。此前,如果检测到延迟加载的路由,而且你在tsconfig.json中手工指定了一组files或include,那这些路由会自动化处理。而如今,根据TypeScript规范,我们不再这么干了。默认情况下,CLI对TypeScript的配置中没有files或include,因此多数开发者不会受影响。

Angular表单添加updateOn Blur/Submit

这样可以根据blur或submit来运行验证和更新值的逻辑了,不必再单纯依赖input事件。

表单对应用很重要,如果有服务端验证,或者验证或更新值会触发较慢的操作,你当然希望它少跑几次。现在你可以在控件层面控制验证和更新值的时机了,也可以在表单层面设置。

此外,你现在可以直接在选项中指定asyncValidators,而不是通过第三个参数指定。

模板驱动的表单

以前

<input name="firstName" ngmodel=""/>
Copy after login
Copy after login

以后

<input name="firstName" ngmodel=""/>
Copy after login
Copy after login

或者

<form [ngFormOptions]="{updateOn:&#39;submit&#39;}">
Copy after login

反应式表单

以前

new FormGroup(value);
new FormControl(value, [], [myValidator])
Copy after login

以后

new FormGroup(value, {updateOn: &#39;blur&#39;}));
new FormControl(value, {updateOn: &#39;blur&#39;, asyncValidators: [myValidator]})
Copy after login

RxJS 5.5

我们已经把使用的RxJS更新到5.5.2或更高版本。这个新发布的RxJS可以让开发完全摆脱之前导入机制的副作用,因为我们以新的lettable operators的方式使用了RxJS。这些新操作符消除了副作用,以及之前导入操作符中“patch”方法存在代码切割和“tree shaking”等问题。

不再这样:

import { Observable } from &#39;rxjs/Observable&#39;;
import &#39;rxjs/add/operator/map&#39;;
import &#39;rxjs/add/operator/filter&#39;;
names = allUserData
.map(user => user.name)
.filter(name => name);
Copy after login

现在这样:

import { Observable } from &#39;rxjs/Observable&#39;;
import { map, filter } from &#39;rxjs/operators&#39;;
names = allUserData.pipe(
  map(user => user.name),
  filter(name => name),
);
Copy after login

此外,RxJS现在发行了一个使用ECMAScript Modules的版本。新Angular CLI会默认拉取这个新版本,让包大小有明显减小。如果你没使用Angular CLI,那还是应该指向这个新版本。相关文档在此:Build and Treeshaking。

新的路由器生成周期事件

我们给路由器添加了新的生命周期事件,让开发者可以跟踪running guard启动到激活完成的各个阶段。这些事件可在有子组件更新时,在一个特定的路由器出口上展示加载动画,或者测量性能。

新的事件(按顺序)是GuardsCheckStart、ChildActivationStart、ActivationStart、GuardsCheckEnd、ResolveStart、ResolveEnd、ActivationEnd、ChildActivationEnd。以下是一个使用这些事件启动和停止加载动画的示例:

class MyComponent {
  constructor(public router: Router, spinner: Spinner) {
    router.events.subscribe(e => {
      if (e instanceof ChildActivationStart) {
        spinner.start(e.route);
      } else if (e instanceof ChildActivationEnd) {
        spinner.end(e.route);
      }
    });
  }
}
Copy after login

如何更新

Here is the Angular Update Guide, which tells you the entire process and what to do before updating, as well as the steps to update the application, and prepare for future versions of Angular.

We have deleted many previously abandoned APIs (such as OpaqueToken) and also announced some new abandoned items. These changes are detailed in the guide above.

Known issues

There are currently known issues related to source map. Some source maps will report "undefined source" errors.

The official introduction is as follows: We are happy to announce the release of Angular 5.0.0 - Pentagonal Donut! This is another major version, containing new features and fixing many bugs. It once again reflects our consistent goal of making Angular smaller, faster, and better to use. We also hope to become familiar with the new version as soon as possible. Today’s software updates too quickly. If the version does not adapt to us, we must adapt to the version!

Related reading:

Understanding the role of APP_INITIALIZER in Angular

angular2's method of packaging and building Android APP environment

AngularJs form validation method

The above is the detailed content of The magic of Angular 5.0. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template