【问题标题】:Angular 2 router navigates undefinedAngular 2 路由器导航未定义
【发布时间】:2017-01-31 09:33:05
【问题描述】:

每次点击链接并加载新组件时,都会抛出以下错误。

该区域显示的 responsive-height.component.ts:111 行是错误的,那里没有 http 连接。

在以前的 Angular 版本中,这只发生在构建文件中,而不是在开发环境中,但在 2.2 之前,它也发生在开发模式中。

不知道问题是和angular2-router还是angular-cli有关。

目前我使用 angular 2.3.1 和 angular-cli@1.0.0-beta.26。

有什么想法吗?

更新: 我的路由就在那里,中间删除了几个相同的,通过foo bar改了一些域名。

const routes: Routes = [
  {
    path: '',
    component: Component1,
    pathMatch: 'full'
  },
  {
    path: 'foo/bar',
    component: Component2
  },
  {
    path: 'user/profile',
    component: ProfileComponent
  },
  {
    path: '404',
    component: NotFoundComponent
  },
  {
    path: '**',
    redirectTo: '404',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class RoutingModule {
}

更新 2: 应用程序正常工作,没有奇怪的行为。但是这个错误被抛出,我想修复它。

更新 3:

app.module:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ErrorModule,
    HeaderModule,
    HttpModule,
    SharedModule,
    RoutingModule,
    UserModule
  ],
  providers: [
    {
      provide: LOCALE_ID,
      useValue: window.navigator.userLanguage || window.navigator.language
    },
    {provide: RequestOptions, useClass: DefaultRequestOptions},
    {provide: ConnectionBackend, useClass: XHRBackend},
    {provide: Http, useExisting: HttpInterceptor},
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

【问题讨论】:

标签: angular angular2-routing angular2-router3


【解决方案1】:

对于没有childrenredirect的空路径路由,需要pathMatch: 'full'

  {
    path: '',
    component: Component1,
    pathMatch: 'full'
  },

否则路由器会一直寻找子路由。

【讨论】:

  • 好的,但不能解决问题。我在上面改了,对吗?
【解决方案2】:

我发现了错误,css 文件中的background-image: none 导致了该错误。

【讨论】:

    【解决方案3】:

    缺少组件声明或导入路径错误

    declarations: [
        AppComponent,
        Component1,
        Component2
        ...    
      ]
    

    检查您的路径。提供plunker with your code

    app.routes.ts:

    const routes: Routes = [
      {
        path: '',
        component: HeaderComponent
      },
      {
        path: 'shared',
        component: SharedComponent
      },
      {
        path: '**',
        redirectTo: '404'
      }
    ];
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule],
      providers: []
    })
    export class RoutingModule {
    }
    

    shared.module.ts 类似于 header.module.ts

    @NgModule({
      imports: [
        CommonModule    
      ],
      declarations: [SharedComponent]
    })
    export class SharedModule { }
    

    没有错误的路线。

    【讨论】:

    • 所有组件都在导入的模块中声明。并且没有懒惰的路线。所以这不是问题
    • 所有组件都声明了,在哪里可以看到呢?提供工作 plunker 或 pastebin 等。检查组件声明的路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2017-12-03
    • 2018-09-25
    相关资源
    最近更新 更多