【问题标题】:import statements in angular 2角度 2 中的导入语句
【发布时间】:2017-10-19 14:52:44
【问题描述】:

如果我在应用程序模块中导入,例如ElementRef 并且在导入服务时,该服务使用 ElementRef,我是否必须在服务中再次导入 ElementRef?

或更笼统地说:我可以吗,例如在 app.module 中,从 angular/core 中导入所有需要的元素,并使它们可用于所有指令、管道和服务,这些指令、管道和服务也在 app.module 中导入。

【问题讨论】:

  • 不,你不能,不
  • 您将 Angular 模块与 ES6 模块混淆了。这些是非常不同的事情。 ES6 模块用于避免全局变量。 Angular 模块用于将组件、指令和管道组合在一起,并定义一些提供程序。

标签: angular typescript import ecmascript-6


【解决方案1】:

你需要将它们导入你需要使用它们的地方。

因此,在AppModule 中,您将导入它们以将它们添加到providersdeclarationsimports 等。

并且在您的组件、指令、管道、模块、服务等中。如果您需要使用它们,则需要再次导入它们。

例子:

AppModule

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 可以使用它的导入

    【讨论】:

    • 你能解释什么是错的吗? .导入只能在该类中使用
    • 这是不正确的。 imports 被模块用来引用其他模块。它们与课程无关。需要明确的是,我不是指 Angular 的 NgModules,我指的是 JavaScript 模块。
    • 已针对使用 Typescript 的 Angular 2 提出了该问题。所以我的回答是上下文。模块只是类,带有特殊的装饰器,例如:- export class AppModule { }。当您将 @NgModule 添加到该 AppModule 类时,该类将成为一个模块。您在 AppModule 类中导入的任何内容都仅供 AppModule 使用
    • 事实并非如此。这是一个完整的模块:export default "hello";
    • 这个问题很模糊,但它清楚地从'@angular/core'; 询问ElementRef 此外,它还询问,当使用使用ElementRef 的服务时,是否需要从@987654330 导入ElementRef再次@
    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 2017-11-04
    • 2017-10-18
    • 2023-03-11
    • 1970-01-01
    • 2017-01-01
    • 2014-03-04
    • 2023-02-15
    相关资源
    最近更新 更多