繁体   English   中英

与Angular 2打字稿等效的ES6

[英]ES6 equivalent of this Angular 2 typescript

我有这个打字稿,我想写等效的ES6。 我正在学习angular 2,并且宁愿使用ES6而不是打字稿,并且所有示例都在ES5或打字稿中。 如果我看到此代码是如何在ES6中编写的,那么我应该可以从打字稿中获取任何需要编写的新代码,并将其从那里获取。 干杯。

'use strict';
import {Component, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app',
  template: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyApp {
  constructor() {
    this.name = 'Max';
  }
}

ES6相当于你的代码是在这个普拉克 我通过添加服务来演示parameters属性(请参见下文),对您的代码进行了一些更改。

说明

我认为您不知道如何将装饰器和类型转换为ES6。

  1. 要替换类装饰器(例如ComponentDirective ),请向组件添加批注属性。 您可以使用静态的getter为此:

     class App { static get annotations() { return [ new Component({ selector: 'my-app', template: '<h1>Hello, {{ name }}</h1>', providers: [Service] }) ]; } // ... } // or just add `annotation` after class declaration App.annotations = [ new Component({ selector: 'my-app', // ... }) ]; 
  2. 要替换参数修饰符(例如@Inject )和类型( constructor(type: Type) ),请向组件添加parameters属性。 同样,您可以为此使用静态吸气剂

     class App { // ... static get parameters() { return [[Service]]; } constructor(service) { this.name = service.getName(); setTimeout(() => this.name = 'Max', 1000); } } // or just add `parameters` after class declaration App.parameters = [[Service]]; 

装饰器(例如@Component )是有效的EcmaScript 7建议 通过使用TypeScript编译器编译代码并查看输出,可以看到“等效” ES6代码:

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Component, bootstrap } from 'angular2/angular2';
// Annotation section
let MyApp = class {
    constructor() {
        this.name = 'Max';
    }
};
MyApp = __decorate([
    Component({
        selector: 'my-app',
        template: '<h1>Hello {{ name }}</h1>'
    })
], MyApp);

稍微清理一下但不是100%等效于TypeScript输出的是:

import { Component, bootstrap } from 'angular2/angular2';
// Annotation section
let MyApp = class {
    constructor() {
        this.name = 'Max';
    }
};
MyApp = Component({
    selector: 'my-app',
    template: '<h1>Hello {{ name }}</h1>'
})(MyApp) || MyApp;

当然,由于所有这一切仍处于提议阶段,装饰器的语法或语义将来可能会更改,因此您不一定要永远依靠它们以这种方式工作。

(还请注意,ES6模块内的“使用严格”编译指示没有任何意义;根据规范,ES6模块内的所有代码已按严格模式运行。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM