【问题标题】:Angular how to share interfaces across the appAngular 如何在应用程序之间共享界面
【发布时间】:2017-12-17 22:04:50
【问题描述】:

所以我有一个interfaces.ts 文件,看起来像这样:

export interface Auction{ $key?:string; $auctioneer:string;  ... }
export interface Item{ $key?:string; condition?:string; description?:string; ...}
export interface Bid{  $key?:string;  amount:number;  auction:string; ...}
and so on  ...

现在我可以通过调用在每个组件/服务中导入这些接口:

import { Auction,Item,Bid } from './interfaces';

但是如何导入 interfaces.ts 文件,以便所有接口都可以在全球范围内使用?

【问题讨论】:

  • 全球?你能解释一下吗?
  • 全局 - 这意味着在每个组件或服务中
  • 如果您必须在组件中使用interfaces.ts 中定义的那些api,您必须将它们导入该组件以及需要它们的其他组件。如果您没有在该特定组件中导入它,您将被标记为错误“找不到名称 [...]”。

标签: angular typescript


【解决方案1】:

在您的应用程序模块中添加这个,其中 InterfaceOne 和 InterfaceTwo 将是您的接口。这样做的缺点是,您的应用程序模块将变得更大,您拥有的接口越多。最好将接口放在单独的文件中并以相同的方式完成。不过我不知道该怎么做。

declare global {

   export interface InterfaceOne {},
   export interface InterfaceTwo {},
   //more interfaces

}

【讨论】:

    【解决方案2】:

    您必须在每个要使用这些接口的组件/服务中导入 interfaces.ts。

    你能做的最接近的事情(可能会节省一些写作)是:

     import * as foo from './interfaces';
    
        变量项:foo.Item;
        var 拍卖:foo.Auction;
        var 出价: foo.Bid;
    

    如果不导入interfaces.ts,就根本找不到接口的名字。

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 1970-01-01
      • 2016-08-29
      • 2020-08-28
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多