Angular6 开发探索 - 知乎日报

最近利用空余时间研究学习了前端“三剑客”之 —— Angular。Angular 是一个开发平台。它能帮你更轻松的构建 Web 应用。Angular 集声明式模板、依赖注入、端到端工具和一些最佳实践于一身,为你解决开发方面的各种挑战。Angular 为开发者提升构建 Web、手机或桌面应用的能力(好官方~~~)。好了,接下来结合自己做 DEMO 的过程来说说。

github >> https://github.com/Hancoson/ng-zhihuDaily Star Star Star ~~

开始

运行

安装

全局安装 Angular CLI

1
npm install -g @angular/cli

新建项目

1
ng new {my-app}

启动

1
2
cd my-app
ng serve --open

或者你可直接克隆本实例

1
2
3
4
5
6
7
git clone https://github.com/Hancoson/ng-zhihuDaily.git

# 1
npm i

# 2
npm start

Angular CLI 使用

添加功能

1
2
3
4
5
6
7
8
ng g cl my-new-class #新建 class
ng g c my-new-component #新建组件
ng g d my-new-directive #新建指令
ng g e my-new-enum #新建枚举
ng g m my-new-module #新建模块
ng g p my-new-pipe #新建管道
ng g s my-new-service #新建服务
ng g m route --routing #新建 route

说明:

  • g - generate
  • cl - class
  • c - component
  • d - directive
  • e - enum
  • m - module
  • p - pipe
  • s - service

备注

不生成单元测试文件

1
--spec=falses

设置默认样式

希望自己的项目使用 Scss 或者 Less 的时候怎么办呢?看看下面:

新建项目:

1
ng new {project-name} --style=scss

在已有项目中设置:

手动修改angular.json文件,添加如下内容即可:

1
2
3
4
5
"schematics": {  
"@schematics/angular:component": {
"styleext": "scss"
}
},

结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
├── README.md
├── angular.json # Angular CLI 的配置文件。
├── dist # 构建目录
├── e2e # 在 e2e/ 下是端到端(end-to-end)测试
├── node_modules # 依赖
├── package.json
├── src
│   ├── app
│   │   ├── app.component.css #根组件样式
│   │   ├── app.component.html #根组件模版
│   │   ├── app.component.spec.ts #根组件单元测试
│   │   ├── app.component.ts # 根组件
│   │   ├── app.module.ts # 定义 AppModule,根模块为 Angular 描述如何组装应用
│   │   ├── components # 组件集
│   │   │   └── home
│   │   │   ├── home.component.html # 组件模版
│   │   │   ├── home.component.scss # 组件样式
│   │   │   ├── home.component.spec.ts # 组件单元测试
│   │   │   └── home.component.ts # 组件逻辑
│   │   ├── constants # 项目静态配置
│   │   └── route # 路由
│   ├── assets # 静态资源
│   ├── browserslist # 一个配置文件,用来在不同的前端工具之间共享目标浏览器
│   ├── environments # 各环境配置文件
│   ├── index.html # 主页面的 HTML 文件
│   ├── karma.conf.js # 给Karma的单元测试配置
│   ├── main.ts # 应用的主要入口点
│   ├── pipe # 管道/过滤器
│   ├── polyfills.ts # 低版本浏览器支持配置
│   ├── styles.scss # 这里是你的全局样式
│   ├── test.ts
│   ├── tsconfig.app.json
│   ├── tsconfig.spec.json
│   ├── tslint.json # 额外的 Linting 配置
│   └── utils # 工具函数
├── tsconfig.json # TypeScript 编译器的配置
└── tslint.json # 给TSLint和Codelyzer用的配置信息

主要技术点

模块

Angular 应用是模块化的,它拥有自己的模块化系统,称作 NgModule。 一个 NgModule 就是一个容器,用于存放一些内聚的代码块,这些代码块专注于某个应用领域、某个工作流或一组紧密相关的功能。 它可以包含一些组件、服务提供商或其它代码文件,其作用域由包含它们的 NgModule 定义。 它还可以导入一些由其它模块中导出的功能,并导出一些指定的功能供其它 NgModule 使用。

NgModule 是一个带有 @NgModule 装饰器的类。@NgModule 装饰器是一个函数,它接受一个元数据对象,该对象的属性用来描述这个模块。其中最重要的属性如下。

  • declarations(可声明对象表) —— 那些属于本 NgModule 的组件、指令、管道。
  • exports(导出表) —— 那些能在其它模块的组件模板中使用的可声明对象的子集。
  • imports(导入表) —— 那些导出了本模块中的组件模板所需的类的其它模块。
  • providers —— 本模块向全局服务中贡献的那些服务的创建器。 这些服务能被本应用中的任何部分使用。(你也可以在组件级别指定服务提供商,这通常是首选方式。)
  • bootstrap —— 应用的主视图,称为根组件。它是应用中所有其它视图的宿主。只有根模块才应该设置这个 bootstrap 属性。
1
2
3
4
5
6
7
8
9
10
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [ BrowserModule ],
providers: [ Logger ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

组件

组件控制屏幕上被称为视图的一小片区域。

1
2
3
4
5
6
7
8
9
10
11
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
/*
……
*/
}
  • selector:是一个 CSS 选择器,它会告诉 Angular,一旦在模板 HTML 中找到了这个选择器对应的标签,就创建并插入该组件的一个实例。
  • templateUrl:该组件的 HTML 模板文件相对于这个组件文件的地址。
  • providers:是当前组件所需的依赖注入提供商的一个数组。
  • styleUrls:组件所需的样式资源。

路由

路由定义 会告诉路由器,当用户点击某个链接或者在浏览器地址栏中输入某个 URL 时,要显示哪个视图。

1
2
3
4
5
6
7
8
9
10
11
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './../components/home/home.component';

const myRoute: Routes = [
{ path: '', component: HomeComponent }
];

export const appRoutes = RouterModule.forRoot(
myRoute,
{ enableTracing: true }
)

典型的 Angular 路由(Route)有两个属性:

  • path:一个用于匹配浏览器地址栏中 URL 的字符串。
  • component:当导航到此路由时,路由器应该创建哪个组件。

RouterModule.forRoot():初始化路由器,并让它开始监听浏览器中的地址变化

管道

切割字符串

  • 新建管道文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import { Pipe, PipeTransform } from '@angular/core'

    @Pipe({
    name: 'SliceStr'
    })

    export class SliceStrPipe implements PipeTransform {
    // start和end及extraStr后面都跟随了一个问好,代表这个为可选参数而不是必选的
    // 功能就是给出截图的启示,然后是否拼接你自定义的字符串(...)等
    transform(value: string, start?: number, end?: number, extraStr?: string): string {
    if (value) {
    if (typeof (start) === 'number' && typeof (end) === 'number') {
    if (value.length > end && extraStr && typeof (extraStr) === 'string') {
    return value.slice(start, end) + extraStr.toString();
    } else {
    return value.slice(start, end);
    }
    } else {
    return value;
    }
    } else {
    return value;
    }
    }
    }
  • 引入

    1
    2
    3
    4
    5
    6
    7
    8
    import { SliceStrPipe } from '../pipe/slicestr.pipe'
    // ...
    @NgModule({
    declarations: [
    SliceStrPipe
    ],
    // ...
    })
  • 使用

    1
    <p class="title">{{item.title|SliceStr: 0:20:'...'}}</p>

相关项目参考


参考资料: