【问题标题】:ORIGINAL EXCEPTION: No provider for Router! angular 2 RC5原始例外:没有路由器供应商!角 2 RC5
【发布时间】:2016-09-07 14:13:52
【问题描述】:

无法使用 this.router.navigate。

这是我的: app.module.ts

    import {NgModule, NgModuleMetadataType}      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {FormsModule}    from '@angular/forms';
    import { HttpModule } from '@angular/http';
    ...
    import {routing} from "./app.routing";
    import {entry} from "./entry.component";
imports: [ 
        BrowserModule,
        FormsModule,
        routing,
        HttpModule,
    ],

测试组件

import { Component } from '@angular/core';
import {HttpClient} from "./HttpClient.component";
import {Router} from "@angular/router-deprecated";

@Component({
    templateUrl: 'templates/entry.html'
})
export class entry {
    ...
    constructor(head:HeaderComponent, private httpClient: HttpClient, private router: Router) {
        this.httpClient = httpClient;
    }
    nav_test(){
        this.router.navigate(['search']);
    }
}

和app.routing

import { Routes, RouterModule } from '@angular/router';
const appRoutes: Routes = [
    {
        path: '',
        redirectTo: '/home',
        pathMatch: 'full',
    },
    {
        path: 'home',
        component: HomeComponent
    },
    {
        path: 'search',
        component: SearchComponent

    }

];
export const routing = RouterModule.forRoot(appRoutes, {useHash: true});

最后我有这个错误:

异常:错误:未捕获(承诺中):异常:./entry 中的错误 类 entry_Host - 内联模板:0:0 原始例外:路由器没有提供者!

提前谢谢你!

【问题讨论】:

    标签: javascript angular typescript angular2-routing


    【解决方案1】:

    问题在于您的测试组件导入,

    你正在使用

    import {Router} from "@angular/router-deprecated";
    

    你应该使用,

    import { Router } from '@angular/router';
    

    希望这会有所帮助!

    【讨论】:

    • 哈哈,谢谢你的回答,我迟到了一分钟xD
    • 不知何故 Angular 团队仍在维护路由器已弃用,它应该启动一些警报,机器应该着火了,如果你正在使用它.. LOL,干杯!!
    【解决方案2】:

    不确定 useHash: true 是如何工作的,但我在 @NgModule 中指定了定位策略:

    providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}]

    而且我使用的是最新的路由器,而不是弃用的路由器。

    工作的 RC.6 代码示例在这里:https://github.com/Farata/angular2typescript/tree/master/chapter3/router_samples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-22
      • 2017-08-07
      • 2017-01-21
      • 2016-11-27
      • 1970-01-01
      • 2016-11-17
      • 2016-12-20
      • 2016-11-07
      相关资源
      最近更新 更多