![fe6e4a75ae1add0fc6c65f20023f122b.png](https://img-blog.csdnimg.cn/img_convert/fe6e4a75ae1add0fc6c65f20023f122b.png)
在 Angular 中,你会看到这样的语法:
import { Component } from '@angular/core';
我们把 { things }
这部分的写法加做解构,这是ES6和TypeScript提供的特性。
在 ES6 中,你可以使用解构从数组和对象中提取值并赋值给独特的变量。
ES6 之前是如何提取数组的值
const point = [10, 20, 30]
const x = point[0];
const y = point[1];
const z = point[2];
console.log(x, y, z) // log 10, 20, 30
ES6 之前是如何提取对象中的值
const people = {
name: 'Johnson',
age: 30
}
const name = people.name;
const age = people.age;
console.log(name, age) // log Johnson, 30
解构
解构数组中的值:[]
表示被解构的数组,x, y, z
表示要将数组中的值存储在其中的变量。
const point = [10, 20, 30];
const [x, y, x] = point;
console.log(x, y, x)
// 还可以忽略值,可以这样
const [x, , z] = point;
解构对象中的值:
花括号{}
表示被解构的对象,nage, age
表示要将对象中的属性存储到其中的变量,无需指定要从其中提取值的属性。
const people = {
name: 'Johnson',
age: 30
}
const { name, age } = people;
console.log(name, age) // log Johnson, 30
你还可以指定在解构对象时要选择的值。例如
let { name } = people
再回头看看 Angular 的代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
你就明白,import
导入了 Angular 核心的 Component
接口,在装饰器中的元数据selector, templateUrl, styleUrls
就要遵守接口的规范,类型不对,检查会出现错误,编译也不会通过。
// node_modules/@angular/core/src/metadata/directives.d.ts
export interface Component extends Directive {
changeDetection?: ChangeDetectionStrategy;
viewProviders?: Provider[];
moduleId?: string;
templateUrl?: string;
template?: string;
styleUrls?: string[];
styles?: string[];
animations?: any[];
encapsulation?: ViewEncapsulation;
interpolation?: [string, string];
entryComponents?: Array<Type<any> | any[]>;
preserveWhitespaces?: boolean;
}