【教练的秘方】开始学习Angular2的第一步

这篇文章是由G’s ACADEMY TOKYO的培训师/导师所写的投稿。在课程中提出的一些小问题和疑问,以及培训师对感兴趣的新技术等都会被无章法地记录下来。

angular2.png

你好!我是Z Academy的导师岸。

JavaScript框架之一AngularJS的最新版本”Angular2″的正式发布即将临近!

在这次文章中,我将介绍一种非常简单的方法,让您能够快速轻松地尝试Angular2!

在Angular2上执行类似于Hello World的操作

以下的教程是基于下面的官方教学(英语):
https://angular.io/docs/ts/latest/quickstart.html
Angular2可以用JavaScript、TypeScript和Dart来编写,但我们推荐使用TypeScript进行学习。

感谢您的指正,我已经将步骤更改为rc.5的内容。

环境建设

创建一个用于运行应用程序的文件夹(以下简称应用程序文件夹)。

$ mkdir angular2-quickstart
$ cd angular2-quickstart

在本地安装npm包。
如果您没有安装Node.js,请从这里安装。

npm可以通过以下命令进行安装。

$ npm install npm -g

将以下4个文件创建在应用程序文件夹的根目录下。

1. package.json是一个定义应用程序所使用的包和脚本的文件。

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.5",
    "@angular/compiler": "2.0.0-rc.5",
    "@angular/core": "2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "2.0.0-rc.5",
    "@angular/router": "3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.15",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
}

2. tsconfig.json- TypeScript编译器的配置文件

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

3. typings.json – TypeScript 的定义文件

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160807145350"
  }
}

4. “systemjs.config.js” 是 SystemJS 的配置文件。

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

安装package.json中记录的每个npm包。

$ npm install

有时候可能不会生成 typings 文件夹,如果出现这种情况,请手动安装。

$ npm run typings install

建立文件

我会在应用程序文件夹的根目录下创建一个名为app的文件夹。

$ mkdir app

我們會在應用程式資料夾的根目錄下建立以下三個檔案。

1. app.component.ts – 包含应用程序组件的文件

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

2. app.module.ts – 包含了组成应用程序的模块的文件描述

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

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

3. main.ts -调用启动应用程序所必需的文件

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

另外,在应用程序文件夹的根目录下,创建HTML文件和CSS文件。

<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
/* Master Styles */
h1 {
  color: #369;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 250%;
}
h2, h3 {
  color: #444;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: lighter;
}
body {
  margin: 2em;
}

最终文件的结构如下所示。

angular2-quickstart
|
├─app
|  ├─app.component.ts
|  ├─app.module.ts
|  └─main.ts
├─node_modules ...
├─typings ...
├─index.html
├─package.json
├─styles.css
├─systemjs.config.js
├─tsconfig.json
└─typings.json

执行

使用以下命令进行执行。

$ npm start

如果顺利的话,将显示以下界面。

angular2_demo1.png

尝试更改Angular组件的内容

我想稍微修改app.component.ts文件中@Component的内容。
我将尝试将app.component.ts文件修改如下。

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: 'template.html',
    styleUrls: ['template.css']
})

class AppComponent { }

在应用程序文件夹的根目录下创建一个模板的html文件,并创建一个适用于它的CSS文件。

<h1>テンプレートです。</h1>
h1 {
    color: red;
}

尝试执行这个…

angular2_demo2.png

我能够确认将HTML和CSS分离成不同的文件,并将它们作为组件的模板和样式进行应用。

然后,我们来尝试一下AngularJS的一个特点,即数据绑定。

我尝试将app.component.ts和template.html改写如下。

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: 'template.html',
    styleUrls: ['template.css']

})

export class AppComponent {
    message = 'コンポーネントからのメッセージです。'
}
<h1>{{message}}</h1>

当试着运行这个……

angular2_demo3.png

我确认了数据绑定已经完成。

我已经向您介绍了一个简单的方法,可以快速尝试Angular2。

如果你对Angular2感兴趣,但却从未接触过它,为什么不尝试一下呢?

这是G’s ACADEMY TOKYO的导师岸所提供的Trainer’s Recipe。