typescript - 在 angular 2 中的导入语句
如果我在应用模块中导入了例如 ElementRef,并且当导入一个服务时,该服务使用了 ElementRef,我是否需要在服务中再次导入 ElementRef?
或者更普遍地说:例如,在 app.module 中,我是否可以从 angular/core 导入所有需要的元素,并使它们对所有的指令、管道和服务可用,这些指令、管道和服务也同样在 app.module 中导入。
答案#1
你需要在需要使用它们的地方导入它们。
所以,在 AppModule 中,你将导入它们以将它们添加到 providers、declarations、imports 等中。
在你的组件、指令、管道、模块、服务等中,如果你需要使用它们,你需要再次导入它们。
示例:
应用模块
import { HttpModule } from '@angular/http';
@NgModule({
bootstrap: [AppComponent],
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
]
})
export class AppModule {
constructor() {
}
}
用户模块
在这里我需要 Http 来执行一些 http 调用,所以我将不得不导入它...
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
HttpModule
],
declarations: [],
exports: [
HttpModule
]
})
export class UserModule{
}
答案#2
导入项只会在被导入的类中可见/使用。
do I have to import ElementRef again in the service
是的,你将不得不导入它,因为服务类无法访问 app.module 中的导入内容。
can I, e.g. in app.module, import all the needed elements from angular/core and make them available to all the directives, pipes and services, which are also imported in app.module
不,这不可能,因为只有 app.module 才能使用它的导入内容
