Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么要导出角度模型接口?_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 为什么要导出角度模型接口?

Javascript 为什么要导出角度模型接口?,javascript,angular,typescript,Javascript,Angular,Typescript,在angular中-模型接口声明如下: export interface PersonInterface { id: number; name: string; } 然后在一些其他组件、服务等中导入此接口并按如下方式使用: ... import { PersonInterface } from './blabla'; ... export class SomeService { person: PersonInterface; } 所以我的问题是-在接口声明中使用export的目

在angular中-模型接口声明如下:

export interface PersonInterface {
  id: number;
  name: string;
}
然后在一些其他组件、服务等中导入此接口并按如下方式使用:

...
import { PersonInterface } from './blabla';
...
export class SomeService {
  person: PersonInterface;
}
所以我的问题是-在接口声明中使用export的目的是什么

如果我不使用导出-我仍然可以在服务中使用它,甚至不需要导入它:

export class SomeService {
  person: PersonInterface;
}
一切正常,没有错误,如果接口Ctrl+单击接口名称,我可以从IDE转到声明。我错过什么了吗


干杯

这是javascript历史上的一个漫长故事。在早期,您必须使用标签以从上到下的顺序手动指定javascript文件。附加脚本后,它的所有声明(如var a=5或函数util{})将可用于它下面的所有脚本和全局脚本。为了实现封装,很难在全局范围内隐藏这些声明,因此需要创建一些新的东西

随后,es模块到达。为了使用其他脚本中的某些函数,您必须在该脚本的最后导出它。这意味着所有其他未导出的声明、函数和变量都被封装起来,隐藏在其他脚本中。这导致了更具弹性的脚本,可以抵御意外修改。如果有人第一次使用一堆脚本,那么在没有任何文档的情况下分析10多个脚本将是一场噩梦。带有导出声明的脚本如下所示:

var a = 5;
function b(){};

module.exports = {
  a: a,
  b: b
}
2012年,创建了Typescript。除了静态类型、适当的类型检查和语法糖等漂亮的功能外,它还提供了一种更好的方法来导出/导入函数、变量和类。语法变成:

从“../other.script”导入某些内容以进行默认导出 为非默认导出从“../other.script”导入{exactOne,exactTwo} 从“../other.script”将*作为整体导入以进行批量导入。
希望这有帮助

如果接口在与组件不同的文件中声明,且未导出和导入,则会引发找不到名称“PersonInterface”的错误。IDE错误将取决于不同的IDE以及IDE中使用的插件。但在ng发球时,你会出现上述错误,这是不应该的。你必须有一个自动导入东西的构建配置,虽然这很奇怪,但从未见过。ng build-prod给了你什么?我正在使用IntelliJ IDEA-我还没有安装插件,IDE也没有给我错误。然而-事实上我看到了错误-SomeService->找不到名称“PersonInterface”。有时,Angular会在开发模式下抑制错误。请执行产品构建或运行ng serve-aot。它应该抛出错误。
var a = 5;
function b(){};

module.exports = {
  a: a,
  b: b
}
// other.script.ts contents
export default const A = '5'; // this will be imported in other file
// other.script.ts contents
export const exactOne = 1;
export const exactTwo = 2;
export const exactThree = 3; // this is NOT imported above, but it's possible to import this const.
const exactFour = 4; // this const cannot be imported at all
// other.script.ts contents
export const a = 'a';
export const b = 'b';

// the AllTogether variable above will be imported like {a: 'a', b: 'b'}