【问题标题】:RC5 NgModules declarationsRC5 NgModules 声明
【发布时间】:2016-08-12 01:27:18
【问题描述】:

将 Angular 2 升级到 RC5 后,我收到如下警告,要求我将组件移动到模块声明中:

NgModule AppModule 通过“entryComponents”使用 AcademylistComponent 但 它既没有申报也没有进口!此警告将成为 final 后出错。

我在我的路由器配置文件中引用了这些组件。看起来像这样:

import {provideRouter,RouterConfig} from '@angular/router';
import {AcademylistComponent} from '../modules/home/component/academyList.component';
import {CourselistComponent} from '../modules/home/component/courseList.component';
import {CreateacademyComponent} from '../modules/home/component/createAcademy.component';
import {ReportsComponent} from '../modules/home/component/reports.component';
import {AuthenticatedGuard} from '../guards/authenticated.guard';

export const routes: RouterConfig = [
{
    path: '',
    redirectTo:'/home',
    terminal:true},
{
    path: 'home',
    canActivate: [AuthenticatedGuard],
    children: [

        {path: '', component: AcademylistComponent},
        {path: 'my-academies', component: AcademylistComponent},
        {path: 'my-courses', component: CourselistComponent},
        {path: 'create-academy', component: CreateacademyComponent},
        {path: 'reports', component: ReportsComponent}

    ]

}

];

export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];

当我将组件移动到 ng 模块的 declarations 数组并将它们导入那里时,路由配置文件确实开始给我 Cannot find name 错误。

那么在这种情况下我该如何使用模块声明呢?

【问题讨论】:

  • 你能告诉我们当前的代码(NgModule)吗?

标签: angular typescript


【解决方案1】:

即使你在路由中声明它们,你仍然需要在 NgModule 中声明路由中使用的组件。

@NgModule({
  declarations: [
    AcademylistComponent,
    //.. and so on
  ], 
  providers: [
    APP_ROUTER_PROVIDERS
  ]
})
export class AppModule {}

【讨论】:

  • 根据angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html:“对于RC5,您可以将组件、指令和管道保留在@Component 元数据的指令和管道属性中...此选项是临时的,用于向后兼容。它将在 Angular 2.0 的最终版本中删除。抢在游戏之前,尽快开始将组件指令和管道移动到模块声明中。”
  • 一个快速的问题。如果我从组件的 providers/directives 数组中移除一个组件/directive/pipe 并将其添加到 NgModule 的 provider 数组中,我还需要在组件中 import ... 那个组件/pipe/directive 吗?我不这样做就会出错。这是正确的方法吗?
  • @TrumanCode 另外,您引用的链接仅要求我们对 app.component 进行此练习。我假设,我们必须对应用程序中的所有组件执行相同的操作?
  • 遵循angular.io/docs/ts/latest/guide/ngmodule.html 的指导 - 我认为这两个问题的答案都是肯定的:您仍然需要导入该模块所需的文件,并且您创建的任何“功能模块”也需要遵循在声明列表中声明组件的约定。
  • 是的,只有在代码里面需要引用组件的时候才需要导入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多