【问题标题】:Angular 2: routerLink not resolvingAngular 2:routerLink 无法解析
【发布时间】:2017-05-13 09:07:07
【问题描述】:
  • Angular 版本:2.1.0
  • 路由器版本:3.1.0

我正在学习 Angular 2 中的路由,单击链接时自定义段没有附加到 URL 中,组件也没有加载。

在地址栏中手动输入段确实有效,组件在<router-outlet></router-outlet> 中加载,但我希望它按预期工作 - 通过单击routerLink 指令内的链接。

我已关注路由器documentation,但结果仍然不佳。

这是一个非常相似的question,但到目前为止还没有找到适合我的解决方案。

我遇到的两个常见解决方案是:

  • “routerLink”拼写错误,区分大小写
  • index.html 的顶部没有<base href='/'>

Chrome 的控制台窗口也没有错误

所以在继续之前,我只想取消明显的解决方案。

这是我为配置自定义路由器所做的:

1.配置自定义路由 (routes.ts)

import { Routes, RouterModule } from '@angular/router';
import { RecipesComponent } from './recipes/recipes.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';

//TODO Fix routing bug (not switching on click or displaying in URL)
export const APP_ROUTES: Routes = [
    {path: '', redirectTo: 'recipes', pathMatch: 'full'},
    {path: 'recipes', component: RecipesComponent},
    {path: 'shopping-list', component: ShoppingListComponent}
];

/*Set routing up for root of app*/
export const routing = RouterModule.forRoot(APP_ROUTES);

2。全局导入路由 (app.module.ts)

import { routing } from './routes';//Custom routes file

    @NgModule({                     
      // Declarations removed for bravity
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        routing
      ],
      providers: [ShoppingListService],
      bootstrap: [AppComponent,]
    })
    export class AppModule { }

3.提供 RouterOutlet 指令 (app.component.html)

<rb-header></rb-header>
<div class="container">
  <router-outlet></router-outlet>
</div>

4.使用静态段实现 routerLink (header.component.html)

<ul class="nav navbar-nav">
    <li><a routerLink="/recipes">Recipes</a></li>
    <li><a routerLink="/shopping-list">Shopping List</a></li>
</ul>

路由器documentation 表示使用routerLink 用于静态段,[routerLink] 用于使用参数传递。我已经尝试了这两种方法,但它们仍然会产生相同的结果。

【问题讨论】:

  • 您可能遇到了异常,因为我看不到您在任何地方导入此组件。您应该为它们创建一个模块并将其导入主 AppModule
  • 你的ts文件编译成js文件了吗?你有什么错误吗?
  • @echonax thatnks 询问 - 不,没有错误,我已将其添加到我的问题中
  • 嗯,为什么您的路由器模块不在@NgModule 内?
  • 对我来说一切都很好。不确定但试试 - routerLink="recipes"

标签: angular angular2-routing


【解决方案1】:

我终于解决了这个问题。

原因是什么?

我的 component.html 中的一个不相关的错误,其中有一个属性将字符串分配给“名称”的未知属性 - Angular 2 在设置“食谱”对象之前编译了字符串插值。

<h4 class="list-group-item-heading">{{recipe.name}}</h4>

修复

我使用了safe navigaton operator 来防止属性路径中出现空值:

<h4 class="list-group-item-heading">{{recipe?.name}}</h4>

结论

路由中没有错误 - 这是我的应用程序的另一部分中的错误,它被 chrome - 开发工具捕获,然后需要修复它才能继续编译应用程序

【讨论】:

  • 那么,错误出现在您未在问题中发布的一段代码中?
  • 是的 - 这就是我更新了我的答案更详细的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
相关资源
最近更新 更多