【问题标题】:Angular 4 imports understanding in module and component fileAngular 4 在模块和组件文件中导入理解
【发布时间】:2018-01-24 22:51:11
【问题描述】:

我正在关注 Angular4-Firebase 集成教程,他们首先在 app.module.ts 中编写以下代码 - 1.

import { AngularFireAuthModule } from 'angularfire2/auth';
    imports: [
      //Some other imports
      AngularFireModule.initializeApp(firebaseConfig),
      //Some more imports
    ],
  1. 然后在 app.component.ts 他们再次导入其他一些与 firebase 相关的东西 -

    从 'angularfire2/auth' 导入 { AngularFireAuth};

现在我有以下问题 -

  1. 为什么他们在 app.module.ts 和 app.comonent.ts 的两个不同位置导入模块/依赖项。为什么他们不能只在 app.module.ts 上这样做。

  2. 据我了解,他们似乎正在 app.module.ts 中导入模块“AngularFireAuthModule”,然后在需要使用的组件文件 (app.component.js) 中导入 Firebase 相关组件它。是这样吗?

如果有人可以分享参考资料以深入了解 Angular 4 中的模块和组件,那就太好了。我正在关注的所有教程都使用 angular cli,它在运行时生成所有内容,并且教程要求在某些情况下更新某些代码让它为他们工作的地方。

提前致谢。

更新 - Here is the link to the said tutorial

【问题讨论】:

  • 教程的链接是什么?
  • 先说app和app.component,然后说app和app.module。是哪一个?
  • 你可能会觉得这篇文章很有帮助Avoiding common confusions with modules in Angular
  • 这与 Angular 没有太大关系。这是一个关于 ES6/TypeScript 模块的问题。你为什么不使用 TypeScript BTW?
  • @Maximus 更新了问题中的链接。

标签: angular


【解决方案1】:

进口声明

导入声明:

import { AngularFireAuthModule } from 'angularfire2/auth';

是 ES 2015 模块功能。在 ES 2015 中,模块是导入或导出某些内容的文件。每个 ES 2015 模块(即代码文件)都需要定义在哪里可以找到它使用的内容。所以如果一个代码文件使用了@component装饰器,那么它需要有一个import语句来定义在哪里可以找到@component装饰器:

import { Component } from '@angular/core';

导入数组

Angular 模块不同于 ES 2015 模块。它们帮助我们组织应用程序。

Angular 模块的 imports 数组定义了应用程序将使用的所有外部模块。

imports: [
  //Some other imports
  AngularFireModule.initializeApp(firebaseConfig),
  //Some more imports
],

我在这里有一个 youtube 视频,讨论 ES 2015 模块和 Angular 模块之间的区别:https://www.youtube.com/watch?v=ntJ-P-Cvo7o&t=6s

【讨论】:

  • 非常感谢您的视频。这对我更好地理解事物有很大帮助。我还有几个问题 -
  • 1.如果我已经在 app.module 中导入了组件,为什么我需要在功能模块中再次导入它。不是所有其他组件都嵌套在 app 组件下吗? 2.我们没有在app.module中指定它与哪个组件相关,我们也没有在ap.component中指定。那么 Angular 是如何绑定它们的呢?
  • 在这里查看我的答案:stackoverflow.com/questions/45724051/…(我什至贴了一张照片。:-)
【解决方案2】:

为了回答你的问题,我可以划分进口

组件导入

文件顶部的导入是 TypeScript 导入,用于使当前文件知道类、接口和变量,并且与角度依赖注入系统无关,这通常发生在第三方库中。

模块导入

导入使用角度依赖注入并且可以导出。这也创建了一个可以与元素共享的新实例(使其非常适合在您的情况下配置参数),而无需多次实例化。

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2021-01-29
    • 2018-10-26
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多