用Angular CLI快速開發Angular2應用程式的入門指南

终于发布了,Angular2!

您知道Angular2中已经设有一个命令行界面(CLI)的开发环境,可以自动生成模板,自动加载更新文件,使得开发速度飞快。

只需安装Angular CLI,即可一次性整合各种开发环境。因此,过去需要设置各种环境,如gulp、grunt、TypeScript的开发风格可能会一下子发生变化。

我希望使用Angular CLI创建一个应用程序,其中包含一个在共享逻辑[MessageService]中获取文本并显示该文本的屏幕组件[HelloComponent]。通过使用服务和组件,我希望您能感受到在Angular中进行开发的大致框架。

让我们来体验Angular2的高速开发。

准备

0.0. 安装Angular CLI

安装Angular CLI非常简单,只需执行npm命令即可。

>npm install -g angular-cli


* ただし、Nodeは4.x.x,npmは3.x.xである必要があります。注意しましょう。 

使用这个方法,各种工具将被集中安装。非常简单!

0.1. 创造一个应用的雏形

首先,我们将按照以下步骤创建一个应用程序。请在该应用程序的文件夹中进行移动。

> ng new MyApp
> cd MyApp

0.2. 执行应用程序的模板。

我们来运行刚刚创建的应用程序吧。请尝试执行下面的命令。

> ng serve

项目已构建,并通过简易服务器提供应用程序。请尝试在浏览器中打开http://localhost:4200/。我相信您将看到Angular 2应用程序在屏幕上运行。

起動画面

之后,每次更新文件时,将自动执行构建,并自动刷新浏览器显示。这确实大大方便了开发工作。

1. 增加服务

在Angular中,您可以使用服务来描述应用程序中的状态和处理。

创建服务模板

这次我们要创建一个Message服务来返回给hello使用的消息。首先让我们创建一个模板。

> ng g service message
installing service
  create src/app/message.service.spec.ts
  create src/app/message.service.ts

请注意,如果在此时输入”Service”和”服务名”,会出现”ServiceService”的重复,请小心操作。

1.2. 服务的实施

让我们在服务中添加一个”getMessage”方法。


export class MessageService {

  constructor() {}

  getMessage(): string{
    return "Hello";
  }
}

1. 最好提前熟悉并熟练处理编译错误。

建议你从现在开始不断遇到各种TypeScript编译(转译)错误。通常情况下,一旦检测到有任何更改,

Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks       Chunk Names
    index.html  2.81 kB       0       
webpack: bundle is now VALID.

在这种情况下,尽管会显示如下内容,但我们可以刻意制造语法错误并进行编译错误。我们可以尝试删除最后的分号并更新保存文件。

  getMessage(): string{
    return "Hello
  }

然后,像下面的控制台一样,输出如下,并且出现了非常长的消息。

ERROR in ./src/app/message.service.ts
Module parse failed: 
(以下略)    

所以,我有点困惑,但只要仔细阅读第一个错误部分(Typescript发现以下错误:message.service.ts(9,24):字符串字面量未结束。),你就会明白字符串字面量没有被正确结束,错误内容就在这里描述。请仔细确认这个错误,然后继续开发即可。

2. 添加组件

那么我们继续工作吧。组件是屏幕的部件。接下来,我们将从先前创建的服务(通用处理)中获取信息,并创建一个能够展示该信息的组件。

2.1.创建原型

让我们使用Angular CLI来生成组件的模板。

> ng g component コンポーネント名

假设我们要创建一个HelloComponent。

> ng g component hello

installing component
  create src/app/hello/hello.component.css
  create src/app/hello/hello.component.html
  create src/app/hello/hello.component.spec.ts
  create src/app/hello/hello.component.ts
  create src/app/hello/index.ts

>

请注意,如果此时将组件名称命名为Component,则会与ComponentComponent重复,请小心。

2.2. 与所创建的服务进行合作。

那么,我们来尝试与之前创建的MessageService进行协作吧。

2.2.1引入服务

首先,对于使用服务的组件,需要按照TypeScript的惯例导入所使用服务的类型。

import { MessageService } from '../message.service'

2.2.2 准备 DI

接下来,我们将设置依赖注入机制,以便可以编辑元数据并获取MessageService。首先,我们将添加providers项来指定注入的服务。

请写下被注入到providers中的MessageService。

@Component({
  providers: [MessageService],
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})

然后添加MessageService作为构造函数的参数,并进行依赖注入。

  constructor(private service: MessageService) { }

现在HelloComponent可以使用MessageService了。

2.3. 调用服务

关于MessageService的使用,对于本例来说,让我们在ngOnInit()函数中通过MessageService#getMessage()来获取值,并将其保存为属性值。

export class HelloComponent implements OnInit {

  constructor(private service: MessageService) { }

  message: string;

  ngOnInit() {
    this.message = this.service.getMessage();
  }

}

2.4. 修改模板。

接下来,我们将使得可以显示获取的值。为此,需要编辑组件的模板。

你好.component.html

<p>
  hello works!
</p>
<p>
{{message}}
</p>

app.component.html的原文是:”paraphrase the following natively in chinese, only need one option : app.component.html”

中文翻译可以是:”请以中文进行翻译,只需要一个选项:app.component.html”

<h1>{{title}}</h1>
<app-hello></app-hello>

将2.5组件合并到主要组件中。

我们来看看在这个状态下的浏览器。

appworks.png

我已经发现该组件正在使用从服务获取的值进行操作。您能看出Angular2开发的强大之处吗?

3. 还要记住其他的指令。

3.1. 使用 ng generate

最后,我们也要记住其他的命令。
生成模板(scafolding)的命令是ng g(generate)。

在TypeScript中,可以创建类和接口。

ひながた用法Componentng g component my-new-componentDirectiveng g directive my-new-directivePipeng g pipe my-new-pipeServiceng g service my-new-serviceClassng g class my-new-classInterfaceng g interface my-new-interfaceEnumng g enum my-new-enum

3.2. 构建应用

在Angular2 CLI中,最新的环境集成了webpack的功能,它可以把JavaScript等文件合并在一起。特别是ng build功能具备产品版本的构建能力。

>ng build --prod

输入该命令后,将创建一个dist目录,并生成产品发布版本。当运行ng serve命令时,会包含一些自动加载的额外代码,但生成的卡哩卡哩的产品版本应用程序将省去这些内容。

3.3. 运行测试

使用`ng g`命令生成的各种文件中,会生成一个名为`*.spec.ts`的Jasmine测试模板文件,遵循Jasmine框架的格式。

那么,我们马上来使用 ng test 命令进行测试。由于创建了 HelloComponent,似乎需要进行一些修正。

3.3.1 进行测试的方法

当执行ng test时,会出现以下错误消息。

Chrome 53.0.2785 (Mac OS X 10.11.6) App: Bakusoku should create the app FAILED
    'app-hello' is not a known element:
    1. If 'app-hello' is an Angular component, then verify that it is part of this module.

问题的原因是app.component.spec.ts文件内无法理解HelloComponent。
让app.component.spec.ts能够使用hello.component吧。

编辑import语句和声明。


//追加
import { HelloComponent } from './hello/hello.component';

describe('App: Bakusoku', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent ,
        HelloComponent //追加
      ],
    });
  });

另外,由于HelloComponent注入了MessageService,所以还需要在hello.component.spec.ts进行修改才行。

让我们修改import文和HelloComponent的生成部分。

import { MessageService } from '../message.service'; //import文を追加

describe('Component: Hello', () => {
  it('should create an instance', () => {
    let service = new MessageService(); //追加
    let component = new HelloComponent(service); //引数を追加
    expect(component).toBeTruthy();
  });
});

现在所有的测试都通过了!

我们要不断地用Jasmin编写测试。

4. 最后

翻译:您可否注意到Angular 2不仅仅是一个应用程序框架,还对开发环境和整个开发工作进行了大量改进呢?

在Angular CLI上构建开发环境只需一次安装,从而大大减少了繁琐的步骤。如果团队合作开发,这将带来很多好处。

目前来看,在ng g命令中似乎还无法生成Angular2的主要功能之一——Angular2的路由器。但是,很快将会进行相应的支持。Angular2的环境在今后还会进一步提高开发效率。

让我们从现在开始使用Angular2来加快开发进程。

bannerAds