我有一个带有定义的接口的文件,我想与我的应用程序的全局名称空间共享。我的第一个尝试是将interfaces.ts
文件导入我的app.module.ts
并将接口放入exports
数组中,但是不能以这种方式使用类型/接口,所以我想到了一些与此小问题相关的问题。
是否需要涉及app.module.ts
才能导出到全局名称空间?
是否有其他方法可以做到这一点(可能是原生javascript方法)?
如果需要执行app.module.ts
,我该如何导入接口,使我的app.module.ts
与应用程序的其余部分共享该接口,这样我就不必不断地{{1 }}放在我的组件中?
答案 0 :(得分:1)
在此处检出全局名称空间:https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html
/*~ Note: If your global-modifying module is callable or constructable, you'll
*~ need to combine the patterns here with those in the module-class or module-function
*~ template files
*/
declare global {
/*~ Here, declare things that go in the global namespace, or augment
*~ existing declarations in the global namespace
*/
interface String {
fancyFormat(opts: StringFormatOptions): string;
}
}
但是要注意:
由于运行时冲突的可能性,该模式有些危险,但是我们仍然可以为其编写声明文件。
答案 1 :(得分:0)
根据Angular官方document的说法,最好是在整个应用程序中使用一个SharedModules
,以便在整个应用程序中使用多个。在此SharedModules
中,您可以为所有常见的事物使用不同的目录应用程序结构,例如Models
,Services
,Interceptors
,Pipe
,components
和等
然后在您需要的主要app.module.ts
和import
上使用此模块。
有关更多信息,请阅读有关PluralSight的有用且快速的指南。