Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.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
如何将TypeScript类集中导入Angular模块?_Angular_Typescript - Fatal编程技术网

如何将TypeScript类集中导入Angular模块?

如何将TypeScript类集中导入Angular模块?,angular,typescript,Angular,Typescript,是否有推荐的方法将TypeScript类导入Angular模块,以便该模块中的每个组件或服务都继承这些定义 核心问题是“为什么导入到模块中的类不能自动导入到该模块中的其他组件中?” 我尝试过将一个类导入模块,如下所示: registration.model.ts: export class Event { id: string; name: string; } 注册.module.ts: import { Event } from './registration.model'; 我还

是否有推荐的方法将TypeScript类导入Angular模块,以便该模块中的每个组件或服务都继承这些定义

核心问题是“为什么导入到模块中的类不能自动导入到该模块中的其他组件中?”

我尝试过将一个类导入模块,如下所示:

registration.model.ts:

export class Event {
  id: string;
  name: string;
}
注册.module.ts:

import { Event } from './registration.model';
我还将其添加到模块中的声明中,但没有任何效果(当我发现它没有任何作用时,我立即将其从声明数组中删除):

registration.service.ts:

getEvents(): Observable<Event[]> {

  return this.http.get(`api/events`)
    .map(response => response.json());

}
我已验证模块中的相对路径是否正确。我可以在模块中将其更改为绝对路径,并在服务中得到相同的错误

后续编辑 多亏了阿德里安的回答,我现在对这一点有了更好的理解。我还发现,您可以从TypeScript模块一次导入多个类,如下所示:

import * as Registration from 'app/models/registration.model'; 
错误本身表示找不到名称事件

问题在于您的相对路径。相对路径不正确


仅供参考:

无需在
声明元数据属性中提及
事件类
。当类必须使用
角度上下文进行操作时,您应该在
声明数组中提及一些内容
,这意味着类是使用
@组件装饰器定义的

因为您使用的是纯Typescript类,所以只需在
registration.service.ts
中导入
事件
类即可

注册.服务.ts

import { Event } from './registration.model or correct relative path';

getEvents(): Observable<Event[]> {   // Now Event[] is declared and will not issue any error.

  return this.http.get(`api/events`)
    .map(response => response.json());

}
import{Event}from./registration.model或correct relative path';
getEvents():已声明可观察的{//Now事件[],不会发出任何错误。
返回此.http.get(`api/events`)
.map(response=>response.json());
}

这不是它的工作原理。为了在应用程序的其他部分中使用事件模型类,您需要在每个部分中导入它。使用或不使用NgModule都无关紧要

NgModule由使用,但在进入该步骤之前,TypeScript编译器需要处理您的代码

在每个要使用此功能的文件中,您都需要导入它,就像在模块中所做的那样(在每种情况下,路径可能不同):


否则,TypeScript将不知道什么是事件以及从何处获取事件。

请查看我问题的最后几行,我知道我可以将其直接导入服务。但这并没有回答我的问题。那么,您似乎对相对路径有问题。相对路径不正确。我100%肯定模块和服务都在同一个目录中,否则添加导入时服务将无法工作。VS代码在模块中的import语句中也没有显示任何错误。@micronyks是正确的,问题可能出在其他地方。将其添加到声明中对代码的工作方式没有影响,因此我当然已将其删除@asmmahmud我没有问题,我正在寻找一种更有效的方法来导入类定义。感谢您的详细回复。
import * as Registration from 'app/models/registration.model'; 
import { Event } from './registration.model or correct relative path';

getEvents(): Observable<Event[]> {   // Now Event[] is declared and will not issue any error.

  return this.http.get(`api/events`)
    .map(response => response.json());

}
import { Event } from './registration.model';