Angular学习前期准备

1,334 阅读7分钟

简介前提条件Node.jsnpm 包管理器Angular配置安装 Angular CLI创建项目运行应用Angular开发创建组件创建服务创建类使用类创建接口引入 JQuery问题记录Type string trivially inferred from a string literal, remove type annotation (no-inferrable-types)tslint注释标记TSLint: Identifier 'errMsg' is never reassigned; use 'const' instead of 'let'. (prefer-const)Angular 中获取 input 标签的内容==和===区别参考文献

简介

Angular (通常是指 "Angular 2+" 或 "Angular v2 及更高版本")是一个基于 TypeScript 的开源 Web 应用框架 由 Google 的 Angular 团队以及社区共同领导。Angular 是由 AngularJS的同一个开发团队完全重写的。

Angular 8 于2019年5月28日发布。特性包括:为所有应用代码进行差异化加载、针对惰性加载路由的动态导入、Web workers、支持 TypeScript 3.4,并且把 Angular Ivy 作为可选的预览特性。Angular Ivy 的可选预览特性包括:

  • 生成的代码在运行时更易于阅读和调试
  • 更快的重新构建
  • 改进了有效载荷的大小
  • 改进了模板类型检查
  • 向后兼容

最值得期待的特性之一是 Ivy,它是一个向后兼容的、基于增量式 DOM 架构的全新渲染引擎。Ivy 从设计之初就考虑到了摇树优化,这意味着应用的发布包中只会包含那些在应用中真正用到的 Angular 部件。

可以预期,每一个版本都会向后兼容前一个版本。Google 承诺每年会进行两次升级。

前提条件

在开始之前,请确保你的开发环境中包括 Node.js® 和 npm 包管理器。

Node.js

Angular 需要 Node.js 版本 10.9.0 或更高版本,最好下载最新版本。

关于 Node.js 的安装及环境配置可以参考:node.js 安装详细步骤教程

验证是否安装配置成功,请在终端/控制台窗口中运行 node -v

npm 包管理器

Angular、Angular CLI 和 Angular 应用都依赖于 npm 包中提供的特性和功能。要想下载并安装 npm 包,你必须拥有一个 npm 包管理器。

本搭建指南使用 npm 客户端命令行界面,Node.js 已经默认安装了它。

npm 可能安装失败,建议先用 npm 安装一下 cnpm,用淘宝镜像安装:https://npm.taobao.org/

npm install -g cnpm --registry=https://registry.npm.taobao.org

要检查你是否安装了 npm 客户端,请在终端/控制台窗口中运行 npm -v

Angular配置

安装 Angular CLI

你可以使用 Angular CLI 来创建项目、生成应用和库代码,以及执行各种持续开发任务,比如测试、打包和部署。

全局安装 Angular CLI。

要使用 npm 命令安装 CLI,请打开终端/控制台窗口,输入如下命令:

npm install -g @angular/cli
或者
cnpm install -g @angular/cli

创建项目

打开终端/控制台窗口找到你要创建项目的目录

ng new 项目名称

ng new angularDemo01

ng new 命令会提示你提供要把哪些特性包含在初始应用中。按 Enter 或 Return 键可以接受默认值。

Angular CLI 会安装必要的 Angular npm 包和其他依赖包。这可能要花几分钟的时间。

ng new angularDemo01 --skip-install

上述命令只会创建项目,但是不会导入相关依赖,之后还需要自己导入依赖。使用 cnpm 命令速度会比较快。

cd angularDemo01
npm install
或者
cnpm install

CLI 会创建一个新的工作区和一个简单的欢迎应用,随时可以运行它。

项目结构大致如下:

index.html 是整个 APP 的页面入口。 代码如下:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularDemo01</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

重点关注 <app-root></app-root><app-root> 相当于是局部页面的占位符。 这个区域是动态加载的,运行时,会被 app.component.html 替换掉。具体来说,就是被 app.component.html 替换掉。

查看根组件 app.component.ts 内容:

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

@Component({
  selector'app-root',
  templateUrl'./app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Tour of Heroes';
}

上述代码把模板定义在一个独立的 HTML 文件中, 再通过 @Component 装饰器中的 templateUrl 属性, 在组件元数据中把它链接到组件,也可以使用 template 属性把它定义为内联的。如下所示:

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

@Component({
  selector'app-root',
  template`
    <h1>{{title}}</h1>
    <h2>My favorite hero is: {{myHero}}</h2>
    `

})
export class AppComponent {
  title = 'Tour of Heroes';
}

模板是包在 ECMAScript 2015 反引号 (`) 中的一个多行字符串。 注意是反引号,不是单引号 (') — 允许把一个字符串写在多行上, 使 HTML 模板更容易阅读。

在后续的学习过程中,我们可以使用 log 方法输出的内容中包括变量信息,注意嵌套在字符串外面的也是反引号,否则无法加载变量的值。如下例所示:

const url = `${this.heroUrl}/?id=${id}`;
this.log(`found heroes matching "${term}"`) :

运行应用

Angular CLI 中包含一个服务器,方便你在本地构建和提供应用。

  1. 转到 workspace 文件夹(angularDemo01)。
  2. 使用 CLI 命令 ng serve--open 选项来启动服务器。
ng serve --open

ng serve 命令会启动开发服务器、监视文件,并在这些文件发生更改时重建应用。

--open(或者只用 -o 缩写)选项会自动打开你的浏览器,并访问 http://localhost:4200/

在终端点击 ctrl+c即可退出。

Angular开发

由于工作习惯使用 IEDA 开发工具,因此只需要安装一下 Angular 插件,后续开发项目,先通过命令行新建项目,然后再用 IEDA 打开进行编辑,安装了 Angular 插件之后编写代码会有提示。

创建组件

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

在终端输入 ng g命令:

F:\workspace\Angular\angularDemo01>ng g
Generates and/or modifies files based on a schematic.
usage: ng generate <schematic> [options]

arguments:
  schematic
    The schematic or collection:schematic to generate.

options:
  --defaults
    When true, disables interactive input prompts for options with a default.
  --dry-run (-d)
    When true, runs through and reports activity without writing out results.
  --force (-f)
    When true, forces overwriting of existing files.
  --help
    Shows a help message for this command in the console.
  --interactive
    When false, disables interactive input prompts.

Available Schematics:
  Collection "@schematics/angular" (default):
    appShell
    application
    class
    component
    directive
    enum
    guard
    interceptor
    interface
    library
    module
    pipe
    service
    serviceWorker
    webWorker

再输入命令

ng g component components/news

在 VsCode 中可以直接创建组件。

比如说新增 product-alerts 组件,该 generator 为组件的三个部分创建了启动文件:

  • product-alerts.component.ts
  • product-alerts.component.html
  • product-alerts.component.css

创建服务

服务是一个广义的概念,它包括应用所需的任何值、函数或特性。狭义的服务是一个明确定义了用途的类。 Angular 把组件和服务区分开,以提高模块性和复用性。 通过把组件中和视图有关的功能与其他类型的处理分离开,你可以让组件类更加精简、高效。

ng g service my-new-service
//创建到指定目录下面
ng g service services/storage

然后在 app.module.ts 里面 import 这个服务,并且声明。

import { StorageService } from './../../services/storage.service';

@NgModule({
  declarations: [// 配置当前项目运行的组件
    AppComponent, NewsComponent, Argular01Component, FormComponent, SearchComponent
  ],
  imports: [// 配置当前模块运行依赖的其他模块
    BrowserModule,
    FormsModule
  ],
  providers: [StorageService],
  bootstrap: [AppComponent]
})

然后在需要用到服务的组件中引用,并且作为参数传给构造函数。

import {StorageService} from '../../services/storage.service';

constructor(public storage: StorageService) {
}

创建类

如同 Java 中的类对象,在 Angular 中也可以这样定义,首先需要创建一个类文件:

ng generate class model/user

代码如下:

export class User {
  id: number;
  name: string;
  // constructor(public id: number, public name: string) { }
}
使用类

在需要使用的地方导入 Hero 类,即可创建 Hero 类型的对象。

import { User } from './user';

//当类中有构造函数时可以这样定义User对象
// export const USERS: User[] = [
//   new User(1, 'hresh1'),
//   new User(2, 'hresh2'),
//   new User(3, 'hresh3'),
//   new User(4, 'hresh4')
// ]

export const USERS: User[] = [
  { id: 101, name: 'hresh1' },
  { id: 102, name: 'hresh2' },
  { id: 103, name: 'hresh3' },
  { id: 104, name: 'hresh4' }
]

创建接口

可以定义类,当然也可以创建接口,然后类可以继承接口。

ng generate interface model/hero

代码如下:

export interface Hero {
  id: number;
  name: string;
}

interface 是把公共属性和方法的提取出来,class 是具体的对象 。

class User implements Hero {

}
等价于
export class User {
  id: number;
  name: string;
}

具体使用场景同在 Java 中一样,根据情况来决定。

引入 JQuery

1、将第三方类库安装到本地

npm install jquery --save
npm install @types/jquery --save

2、将库引入到当前的项目中去

修改.angular-cli.json的"scripts" ,注意路径一定要书写正确。

"scripts": ["./node_modules/jquery/dist/jquery.js"]

3、在组件中引入JQuery

import { Component } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector'app-root',
  templateUrl'./app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  ngOnInit() {
      $("body").css("color""blue");
  }
}

问题记录

Type string trivially inferred from a string literal, remove type annotation (no-inferrable-types)

问题解析:tslint 觉得自己根据右边的"hresh"判断出 name 的类型是 string,所以,认为再写 string 是多此一举。

解决方法:tslint.json 添加"ignore-properties"。不推断类的属性(字段)。

 "no-inferrable-types": [
      true,
      "ignore-params",
      "ignore-properties"
    ]

tslint注释标记

ts文件中使用以下注释来临时忽略规则出现的错误,参考这里

/ tslint:disable /——忽略该行以下所有代码出现的错误提示
/ tslint:enable /——当前ts文件重新启用tslint
// tslint:disable-line——忽略当前行代码出现的错误提示
// tslint:disable-next-line——忽略下一行代码出现的错误提示

TSLint: Identifier 'errMsg' is never reassigned; use 'const' instead of 'let'. (prefer-const)

问题:

var todoList = this.storage.get('todoList');

TypeScript 的 Tslint 又报错了,这回是变量未重新赋值,被强烈建议使用常量修饰符const。

解决方案:打开项目下的 tslint.json 文件,将 prefer-const 设置为 false。 然后将 var 改为 let,修改后的语句为:

// tslint:disable-next-line:prefer-const
let todoList = this.storage.get('todoList');

Angular 中获取 input 标签的内容

document.getElementById('name').value;

该语句执行报错,修改引号之后在控制台是可以得到正确内容。如果想要获取数据,可以改为这样:

const nameInput = document.getElementById('name'as HTMLInputElement;
console.log(nameInput.value);

==和===区别

简单来说: == 代表相同, ===代表严格相同, 为啥这么说呢,

这么理解: 当进行双等号比较时候: 先检查两个操作数数据类型,如果相同, 则进行===比较, 如果不同, 则愿意为你进行一次类型转换, 转换成相同类型后再进行比较, 而===比较时, 如果类型不同,直接就是 false。

比较过程:

  双等号==:

  (1)如果两个值类型相同,再进行三个等号(===)的比较

  (2)如果两个值类型不同,也有可能相等,需根据以下规则进行类型转换在比较:

    1)如果一个是null,一个是undefined,那么相等

    2)如果一个是字符串,一个是数值,把字符串转换成数值之后再进行比较

  三等号===:

  (1)如果类型不同,就一定不相等

  (2)如果两个都是数值,并且是同一个值,那么相等;如果其中至少一个是NaN,那么不相等。(判断一个值是否是NaN,只能使用isNaN( ) 来判断)

  (3)如果两个都是字符串,每个位置的字符都一样,那么相等,否则不相等。

  (4)如果两个值都是true,或是false,那么相等

  (5)如果两个值都引用同一个对象或是函数,那么相等,否则不相等

  (6)如果两个值都是null,或是undefined,那么相等

参考文献

9Angular速查表

Angular8入门学习笔记