【问题标题】:Angular 2 RC5 : No provider for RouterAngular 2 RC5:没有路由器提供者
【发布时间】:2016-12-22 11:39:06
【问题描述】:

我在使用新的 Angular 2 RC5 路由器(路由器版本为 RC1)时遇到问题。

这是我从开发控制台得到的日志:

EXCEPTION: Error in /templates/app.component.html:2:0
ORIGINAL EXCEPTION: No provider for Router!

这是我的 app.modules.ts 的样子:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent }   from './components/app.component';
import { routing } from './app.routes';

@NgModule({
    declarations: [AppComponent],
    imports:      [BrowserModule, RouterModule, FormsModule, HttpModule, routing],
    bootstrap:    [AppComponent],
})
export class AppModule {}

这是我的 boot.ts 文件:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

我的 app.routes.ts 文件...

import { Routes, RouterModule } from '@angular/router';

// Components
import { HomeComponent } from './components/home.component';

const routes: Routes = [
    // Root
    { path: '/', name: 'Home', component: HomeComponent, useAsDefault: true},
];

// - Updated Export
export const routing = RouterModule.forRoot(routes); 

...和我的 app.component.ts 文件:

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

@Component({
    selector: 'app',
    templateUrl: '/templates/app.component.html'
})

export class AppComponent {
    viewContainerRef: any;

    public constructor(viewContainerRef:ViewContainerRef) {
        // You need this small hack in order to catch application root view container ref
        this.viewContainerRef = viewContainerRef;
    }
}

这里有什么我遗漏的吗?

【问题讨论】:

  • "useAsDefault" 不再是有效属性。我还将删除路径属性上的“/”并将 添加到您的 index.html 文件中。
  • 路由“名称”也需要删除。

标签: javascript angularjs typescript routing


【解决方案1】:

在 app.routes.ts 文件中:

添加此导入状态

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

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

这应该可行。

【讨论】:

  • 嘿 @EmmanuelScarabin 添加 ModuleWithProviders 并没有为我解决。我有“没有路由器提供商!”在 app.component.html 中添加 标记后立即出错
  • @SudarP 您还应该检查您是否没有在任何组件中使用“路由器弃用”。这是造成我这个问题的第二个原因。
猜你喜欢
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2016-12-18
  • 1970-01-01
  • 2016-12-19
  • 2016-12-20
  • 2020-06-09
相关资源
最近更新 更多