angular2入门-第一个angular2 App

建立一个angular包括以下步骤:

* 运行环境:安装Node.js

* Step 1: 创建一个app项目,定义好包依赖和指定项目设置

* Step 2: 创建Angular App的根组件(Component)

* Setp 3: 创建一个Angular模块(Module)

* Step 4: 添加`main.ts`,标识Angular的根组件

* Step 5: 添加网页应用`index.html`

* Step 6: 构建并运行App


安装运行环境Node.js

如果你的机器上没有安装Node.js和npm,要先安装,如果已经安装,需要检查一下,Node运行版本是否为4.x和Npm版本为3.x以上。Node下载地址:https://nodejs.org/en/download/ ,如果需要源代码可以自行访问github下载。

$ node -v

$ npm -v


Step 1:创建和配置项目

(1)建立文件夹

$ mkdir angular2

$ cd angular2

(2) 添加包定义和配置文件至angular2目录

- package.json 列出了本Demo依赖的脚本(scripts).更多细节可以查看[Npm包配置](https://angular.io/docs/ts/latest/guide/npm-packages.html)

- tsconfig.json 这里定义了TypeScript编译器的配置。TypeScript是Angular2的主要语言,但由于浏览器不能直接使用TypeScript。详细[TypeScript配置](https://angular.io/docs/ts/latest/guide/typescript-configuration.html#!#tsconfig)可以查看。

- typings.json 标识TypeScript 的定义文件。

- systemjs.config.js 系统配置文件。

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/compiler-cli": "0.5.0",

    "@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/upgrade": "2.0.0-rc.5",

    "core-js": "^2.4.0",

    "reflect-metadata": "^0.1.3",

    "rxjs": "5.0.0-beta.6",

    "systemjs": "0.19.27",

    "zone.js": "^0.6.12",

    "angular2-in-memory-web-api": "0.0.17",

    "bootstrap": "^3.3.6"

  },

  "devDependencies": {

    "concurrently": "^2.2.0",

    "lite-server": "^2.2.2",

    "typescript": "^1.8.10",

    "typings":"^1.3.2"

  }

}

tsconfig.json:


{

  "compilerOptions": {

    "target": "es5",

    "module": "commonjs",

    "moduleResolution": "node",

    "sourceMap": true,

    "emitDecoratorMetadata": true,

    "experimentalDecorators": true,

    "removeComments": false,

    "noImplicitAny": false

  }

}

typings.json


{

  "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"

  }

}

systemjs.config.js


/**

 * 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);

(3) 安装包(package)

这里使用npm来安装package.json里定义的依赖包。

$npm install

$npm run typings install

angular应用开发者依赖npm包管理工具安装和打包所需依赖。

工具类脚本

我们已经在package.json文件中添加一些npm脚本来处理公共的开发任务。

{

  "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"

  }

}

我们在使用npm run方式执行npm脚本加上一个脚本名作为参数可以执行指定的脚本,而有些方法并不需要run关键字。(比如: start,只需npm start即可)

  • npm start - 同时启动编译器和服务器,启动后处于监视模式(watch mode)

  • npm run tsc - 运行一次TyppeScript编译器

  • npm run tsc:w - 使用监视模式运行TypeScript编译器,此时进程将保持运行,等待TypeScript文件更改并重新编译它们

  • npm run lite - 启动lite-server,这是一个轻量级的,静态文件服务器,支持Angular App应用

  • npm run typings - 分别运行typings工具

  • npm run postinstall - 在成功安装完依赖包后自动被调用


Step 2: 建立我们第一个Angular组件

在angular2文件夹中建立子文件夹

mkdir app

在新创建的app文件夹中创建组件文件app/app.component.ts:


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

@Component({

  selector: 'my-app',

  template: '<h1>My First Angular 2 App</h1>'

})

export class AppComponent { }

AppComponent是应用的根(root)

每个Angular应用至少有一个根组件,通常命名为AppComponent,用以主持用户的访问。组件是Angular应用的基本构建单元。一个组件通过关联的模板控制屏幕的一部分。本例只写一个简单的组件,但它有每一个组件都有的基本结构:

- 一个或多个import 表述,用于导入我们需要引用的类。

- 一个@Component 声明,告诉Angular使用哪个模板和如何创建组件。

- 一个 component类,用于控制一个视图(View)的表面和行为。
import

Angular应用是模块化的。它们由很多个功能专一的文件组成。Angular本身就是模块化的,它是几个相关的用于构造我们应用的模块库集合。

当我们需要使用一个模块或库时,我们可以引入(import)它。上面代码中,我们引入了Angular2的核心库,我们使用的@Component注解就是来自于这个库。

@Component 声明

Component是一个装修器函数,需要元数据(metadata,比如一个dom对象)对象作为参数。我们需要在类的顶部使用@符号和传入元数据对象。这类似于java等语言中的注解。参数是一个元数据对象,告诉Angular如何创建和使用该组件。

app/app.compoent.ts(metadata)

@Component({

  selector: 'my-app',

  template: '<h1>My First Angular 2 App</h1>'

})

上面指定了一个元数据,有两个域,selector选择器和template模板。

selector代表组件使用CSS选择器指定了一个HTML元素。这个元素名为my-app。Angrular无论在主HTML的任何位置都创建和展示同一个my-app.

template域指定了这个组件对应的模板,模板写法拓展自HTML语法,告诉Angular如何去渲染组件的视图。这里模板的定义和后端语言的模板相似。如FreeMarker. 一个高级模板包括绑定组件属性的数据,可以标识其它模板,这样,一个Angular应用程序就成了一棵组件树。

Component 类
export class AppComponent{}

当我们要去创建一个实质性的应用时,我们可以用属性和程序逻辑拓展此类。我们使用了export关键字,所以我们可以import这个组件在我们程序中的任何一个位置。


Step 3:编写app.module.ts

建立名为AppModule模块,创建文件app/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 { }

使用NgModule修饰的方法参数如下:

  1. imports - 引入其它模块,每个应用程序都需要引入BrowserModule.

  2. declarations - 这个模块的组件和指令。

  3. bootstrap - 标识根组件,Angular在启动应用程序时应当先启动这些组件。

我们上面编写的app.component.ts被添加到了declarations和bootstrap数组中。

Angular模块引入其他模块

请注意,我们添加BrowserModuleimports数组中。这个模块包含所有Angular在浏览器运行我们的应用所需要代码片段。在Angular众多的模块中,我们最常用的一个是FormModule和下面要介绍的RouterModule,HttpModule.


Step 4: 添加 main.ts

创建文件app/main.ts,添加如下代码:


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

请注意我们引入platformBrowserDynamic方法是从@angular/platform-browser-dynamic,而不是@angular/core。Bootstrapping 不是core,因为启动App的方式不止一种。事实上,大部分应用都是运行在浏览器中的。

但是在不同环境加载不同模块是可行的,我们可以在带有Apache Cordova或者 NativeScript的移动设备上加载App组件。

为什么要分离出main.ts,为什么要分离应用模型和应用组件?而不放在一起?在本文教程中,由于只是简单的应用引导,main.ts和app.module.ts代码量都比较少,完全可以很轻松的合并起来,但是应用复杂时,会增加开发难度。分离还有一个好处是,可以使用不同的环境运行程序,而只需要修改main.ts即可。


Step 5:添加 inex.html

在项目的根目录创建文件index.html,添加如下代码:


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

这个HTML文件值得注意的是

  1. 使用的JavaScript库

  2. SystemJS配置

  3. 标签的使用

库(Libraries)

经过生产实践的测试,达到最短的加载时间我们最先引入core-js,接着是zone.jsreflect-metadata,最后是SystemJS

SystmeJS

SystemJS加载应用和库模块。我们在开始前创建了文件systemjs.config.js,在这个配置文件中,我们首先创建了一个map,对需要用到的模块进行名字的映射,然后注册所有的SystemJS使用到的package.

当Angular在main.ts中调用bootstrapModule方法时,它会读到AppModule元数据,发现AppComponent是一个启动组件,找到my-app选择器,定位到名为my-app的元素标签,在标签中渲染我们应用的View


添加样式

创建style.css文件在项目根目录:


/* 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;

}



Step 6:构建和运行应用

运行命令:

npm start

这个命令运行两个平行的node进程

  1. 监视模式运行TypeScript编译器

  2. 一个名为lite-server静态的Server加载index.html在浏览器,并且当文件有修改自动刷新浏览器。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值