我有一个HeaderComponent
,它将形式{title: string, short_desc: string}
的对象作为其输入属性。
@Component({
selector: 'header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
@Input() data: { title: string, short_desc: string };
constructor() { }
ngOnInit() { }
}
以下是我如何定义将传递给HeaderComponent
的数据:
@Component({
templateUrl: './my-custom.component.html',
styleUrls: ['./my-custom.component.scss']
})
export class MyCustomComponent implements OnInit {
public headerData: {title: string, short_desc: string};
constructor() {
this.headerData = {
title: 'Settings Page',
short_desc: 'Update your settings',
}
}
ngOnInit() { }
}
现在,我需要在很多组件中使用HeaderComponent
。所以我创建了一个文件header-data.ts
如下所示:
export interface HeaderData {
title: string;
short_desc: string;
}
为了使HeaderComponent
工作,在每个使用它的组件中,我需要导入HeaderData
接口。当我决定重组我的应用程序时,这有时看起来很丑陋,并且可能会中断。
我的问题是:如何使用HeaderData
接口,而无需像../../../../hero-data.ts
或内联对象类型定义那样丑陋的嵌套导入。或者也许我所做的不是解决这个问题的最佳方法?
您显然注意到您通常如何从 @angular/...模块在一行中。这就是桶的功能。请查看 Angular 文档中的 Barrel 文件描述。
在阅读该文本时,您必须了解JavaScript模块和Angular模块之间的区别。前者是源文件,后者是用@NgModule修饰的类。
由于interface
不是JavaScript概念,而是TypeScript中的抽象,因此仅在编辑器和转译过程中需要它。模块加载程序不使用接口文件声明。因此,您可以使用技巧并将其声明为 TypeScript 定义。
将文件重命名为 header-data.d.ts,并使用单词 declare
而不是如下所示的export
。
declare interface HeaderData {
title: string;
short_desc: string;
}
因此,TypeScript 将能够在设计时找到HeaderData
名称。此技巧依赖于tsconfig.spec.json
文件中"include"
数组中的"**/*.d.ts"
行。