簡體   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