【问题标题】:Cannot find name 'XXX'找不到名称“XXX”
【发布时间】:2018-06-28 06:34:35
【问题描述】:

当我尝试将路由添加到另一个模块导出的组件时,我的 app.module.ts 文件中出现错误“找不到名称‘日历组件’”。

这是我的 app.module.ts 文件

// Module Import Statements //
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {RouterModule, Routes} from '@angular/router';

import { CalendarModule } from './scripts/calendar/calendar.module';

// Component Import Statements //
import { AppComponent } from './app.component';

// Routes Declaration Statements //

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    CalendarModule,
    BrowserModule,
    NgbModule.forRoot(),
    RouterModule.forRoot([
      {
           path: 'calendar', component: CalendarComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是我的 calendar.module.ts 文件

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { CalendarComponent } from './calendar.component';

@NgModule({
  imports: [
    CommonModule,
    FormsModule
  ],
  declarations: [CalendarComponent],
  exports: [CalendarComponent]
})
export class CalendarModule { }

如您所见,我的日历组件在我的 calendar.Module.ts 文件中声明和导出(calendar.component.ts 存在,但为了清楚我的问题,我将其省略了)。那么,为什么我的应用模块不能识别和解释我试图在路由数组中传递它的组件?

如果有帮助,我正在使用 Angular v5.2.0。

【问题讨论】:

    标签: angular typescript module components


    【解决方案1】:

    您必须在 app.module.ts 文件中添加导入语句。

    import { CalendarComponent } from '[location of calendar component]';
    

    TypeScript imports 语句和 Angular 的 ngModule imports 数组是有区别的。

    import { .. } from '@angular/..' 用于 typescript 导入,这意味着您将使用在 '@angular/..' 位置可用的 typescript 文件中声明的一些标识符(主要是该位置的 index.ts)

    imports: [ module1, module2, ... ] 指定模块列表,其导出的组件/指令/管道应可用于当前模块中的模板。

    模块在它们自己的范围内执行,而不是在全局范围内;这意味着在模块中声明的变量、函数、类等在模块外是不可见的,除非它们使用其中一种导出形式显式导出。相反,要使用从不同模块导出的变量、函数、类、接口等,必须使用其中一种导入形式导入。 块引用

    请点击this链接以获得更清晰的信息。

    【讨论】:

    • 我想我也需要导入它,只是不明白为什么,所以谢谢你的解释。至于我需要的服务,我是否从声明它们的模块中导出它们,然后以类似的方式将它们导入 app.module.ts 中? -- 所以导入整个模块,就像我的日历模块一样,不会带来该模块的组件导出(因为我仍然需要从它们的初始导出位置导入它们——在这种情况下是 calendar.component .ts)?
    • 只要您不在 app.module.ts 中使用它们(只是 app.module打字稿文件)。
    【解决方案2】:

    一个。您还没有在 app.module.ts 中导入 CalenderComponent。

    b.我建议尝试将日历功能实现为子路由

    参考:https://angular.io/guide/router#milestone-4-crisis-center-feature

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2018-07-09
      • 2014-12-20
      • 2016-01-24
      相关资源
      最近更新 更多