如何将接口导出到全局名称空间-angular

时间:2020-09-19 04:58:11

标签: javascript angular typescript

我有一个带有定义的接口的文件,我想与我的应用程序的全局名称空间共享。我的第一个尝试是将interfaces.ts文件导入我的app.module.ts并将接口放入exports数组中,但是不能以这种方式使用类型/接口,所以我想到了一些与此小问题相关的问题。

是否需要涉及app.module.ts才能导出到全局名称空间?

是否有其他方法可以做到这一点(可能是原生javascript方法)?

如果需要执行app.module.ts,我该如何导入接口,使我的app.module.ts与应用程序的其余部分共享该接口,这样我就不必不断地{{1 }}放在我的组件中?

2 个答案:

答案 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中,您可以为所有常见的事物使用不同的目录应用程序结构,例如ModelsServicesInterceptorsPipecomponents和等

然后在您需要的主要app.module.tsimport上使用此模块。 有关更多信息,请阅读有关PluralSight的有用且快速的指南。