【发布时间】: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"