ES5 和 ES6 中的 Angular 2 依赖注入

IT技术 javascript angular ecmascript-6
2021-01-23 07:20:31

这是一个基本的 TypeScript/ES.next 示例,它使用装饰器进行 DI 并遵循框架手册建议的语法:

import {Component, Inject, Injectable, NgModule, OpaqueToken} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

const CONSTANT = { value: 'constant' };
const CONSTANT_TOKEN = new OpaqueToken;
const CONSTANT_PROVIDER = { provide: CONSTANT_TOKEN, useValue: CONSTANT };

@Injectable()
class Service {
  constructor(@Inject(CONSTANT_TOKEN) constant) {
    console.log('Service constructor', constant);
  }
}

@Component({
  selector: 'app',
  template: '...',
  providers: [Service, CONSTANT_PROVIDER]
})
class AppComponent {
  constructor(@Inject(Service) service: Service, @Inject(CONSTANT_TOKEN) constant) {
    console.log('AppComponent constructor', service, constant);    
  }
}

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

在 ES5 中它会如何编写?

如何将同样的事情在做untranspiled ES6 / ES2015?

在这些情况下InjectableInject装饰器如何翻译?

该问题特别适用于具有类但可能使用requireSystem.import代替 ES6 导入的实际 ES6 浏览器实现

2个回答

要在ES5 中使用 Angular 2,你需要这个脚本:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.3/angular2-all.umd.js"></script>

这提供了一个包含所有 Angular 2 的全局变量。现在您可以编写ng.core.Component而不是@Component注释。构造函数的第一个参数是可注入的。

var Component = ng.core
  Component({
    selector: 'hello-cmp',
    template: 'Hello World!',
    viewProviders: [Service]
  .Class({
    constructor: [Service, function (service) { 
      ...
    }],
  });

并告诉注入器我们的服务参数是一个实例 Service

Component.parameters = [[new ng.core.Inject(Service)]];


以下示例显示了 angular2 与ES6的用法

import {Component} from 'angular2/core';
import {Service} from './example.service';

let componentAnnotation = new Component({
  selector: 'world-time',
  inputs: ['timeZones'],
  providers: [Service],
  template: `
    ...
  `
});
export class ComponentExample {
   constructor(service) {
    this._service = service;

   }
...

}

WorldTimeComponent.annotations = [componentAnnotation];
WorldTimeComponent.parameters = [[Service]];

在这个 plunkr 中,您可以找到一个有效的 ES6 示例。

但是你可以通过使用Babel来使用装饰器启用optional[]=es7.decorators(在 webpack 中)或通过将您的配置设置为stage:1.

我更新了我的答案,使 es5/es6 之间的差异更清楚
2021-03-22 07:20:31
angular2-all脚本为 1.5 MB。对于 Web 应用程序来说太多了。
2021-03-27 07:20:31
ES2015 不包括装饰器,问题是关于将 Angular 2 与未编译的代码一起使用。我以前遇到过这种 ES5 语法,但我不确定它应该如何应用于 ES6 类。
2021-03-28 07:20:31
谢谢。请考虑问题中的示例,而不是为了一致性,Service注入constant其中可能是一个重要的细节。您所指的示例使用 2.0.0.beta-11,从那时起发生了一系列重大更改。这是一个带有 'es6' TS 目标的 plunker,它遵循建议的语法并抛出"Can't resolve all parameters for Service: (?).
2021-04-12 07:20:31

Injectable装饰器特定于 Angular 2 的 TypeScript 风格。它使类构造函数能够通过 TypeScript 类型注释为 DI 隐式注释。对于用Inject.

角2个注射剂(类和构造函数)都应该与要注释annotationsparameters引擎盖下的静态属性。

annotations是一个包含new可注入类的 ed 装饰器的数组

function SomeComponent(...) {}
SomeComponent.annotations = [new Componenent(...)];

parameters是一个包含构造函数参数装饰器的数组,每个元素都是一个数组,其中包含一个new用于相应构造函数属性ed 装饰器列表(类似于$injectAngular 1.x 中的属性显式注释):

function Service(someService, anotherService) {}
Service.parameters = [
  [new Inject(SomeService)],
  [new Inject(AnotherService), new Optional, new SkipSelf]
];

所有类装饰器都是从 扩展的TypeDecorator,这意味着它们可以作为函数调用。在这种情况下,使用了所谓的 DSL 语法,它允许将装饰器与Class辅助函数链接起来

var SomeComponent = Componenent(...).Class(...);

Class也可以单独使用,它从给定的定义对象构造一个新类,并允许constructor使用数组注释方法(类似于 Angular 1.x 中的内联数组显式注释):

var SomeService = Class({
  constructor: [[new Inject(SomeService)], function (someService) {}]
});

Classhelper 在最新的框架版本中已被弃用。它应该被 ES5 中的原始函数或第三方类助手替换。装饰器支持与类函数的直接链接,Componenent(...)(ComponentClass).

Angular 2/4 ES6 与 System.import

一个例子

Promise.all([
  System.import('@angular/core'),
  System.import('@angular/platform-browser'),
  System.import('@angular/platform-browser-dynamic')
])
.then(([
  {Component, Inject, Injectable, Optional, NgModule, OpaqueToken},
  {BrowserModule},
  {platformBrowserDynamic}
]) => {

  const CONSTANT = { value: 'constant' };
  const CONSTANT_TOKEN = new OpaqueToken;
  const CONSTANT_PROVIDER = { provide: CONSTANT_TOKEN, useValue: CONSTANT };

  class Service {
    constructor(constant) {}
  }
  Service.parameters = [[new Inject(CONSTANT_TOKEN)]];

  class AppComponent {
    constructor(service, constant) {}
  }
  AppComponent.annotations = [new Component({
    selector: 'app',
    template: '...',
    providers: [Service, CONSTANT_PROVIDER]
  })];
  AppComponent.parameters = [[new Inject(Service)], [new Inject(CONSTANT_TOKEN)]];

  class AppModule {}
  AppModule.annotations = [new NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
  })];

  platformBrowserDynamic().bootstrapModule(AppModule);

})
.catch((err) => console.error(err));

带有 UMD module和ng全局的Angular 2/4 ES5

一个例子

var Class = ng.core.Class;
var Component = ng.core.Component;
var Inject = ng.core.Inject;
var Injectable = ng.core.Injectable;
var NgModule = ng.core.NgModule;
var OpaqueToken = ng.core.OpaqueToken;

var BrowserModule = ng.platformBrowser.BrowserModule;
var platformBrowserDynamic = ng.platformBrowserDynamic.platformBrowserDynamic;

var CONSTANT = { value: 'constant' };
var CONSTANT_TOKEN = new OpaqueToken;
var CONSTANT_PROVIDER = { provide: CONSTANT_TOKEN, useValue: CONSTANT };

// Class helper function that uses A1-flavoured inline array DI annotations
// and creates an annotated constructor
var Service = Class({
  constructor: [[new Inject(CONSTANT_TOKEN)], function (constant) {
    console.log('Service constructor', constant);
  }]
});
// can also be
// function Service(constant) {};
// Service.parameters = [[new Inject(...)], ...];

// when not being `new`ed, Component is a chainable factory that has Class helper method
var AppComponent = Component({
  selector: 'app', 
  template: '...',
  providers: [Service, CONSTANT_PROVIDER]
})
.Class({
  constructor: [
    [new Inject(Service)],
    [new Inject(CONSTANT_TOKEN)],
    function (service, constant) {
      console.log('AppComponent constructor', service, constant);
    }
  ]
});
// can also be
// function AppComponent(...) {};
// AppComponent.annotations = [new Component(...)];
// AppComponent.parameters = [[new Inject(...)], ...];

var AppModule = NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
.Class({ constructor: function () {} });
// can also be
// function AppModule() {};
// AppModule.annotations = [new NgModule(...)];

platformBrowserDynamic().bootstrapModule(AppModule);