-
角度版本:2.1.0
-
路由器版本:3.1.0
我正在学习Angular 2中的路由,并且在单击链接时自定义段不会附加到URL,也不会加载组件 .
手动在地址栏中键入段可以正常工作,组件加载到 <router-outlet></router-outlet>
但不是这样,我希望它按预期工作 - 通过单击 routerLink
指令内的链接 .
我跟着路由器documentation并且仍然有不良结果 .
这是一个非常相似的question但是到目前为止还没有找到适用于我的解决方案 .
我遇到的两个常见解决方案是:
-
Misspelling 'routerLink',区分大小写
-
index.html
顶部没有<base href='/'>
Chrome中的控制台窗口也没有错误
所以在继续之前我只想取消明显的解决方案 .
这是我为配置自定义路由器所做的工作:
1. Config custom routes (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. Import routes globally (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. Supply the RouterOutlet Directive (app.component.html)
<rb-header></rb-header>
<div class="container">
<router-outlet></router-outlet>
</div>
4. Implement routerLink with static segments (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]
用于使用params传递 . 我尝试了两种方法,但它们仍然会产生相同的结果 .
1 回答
我终于解决了这个问题 .
What was the cause ?
我的
component.html
中有一个不相关的错误,其中有一个属性将字符串分配给'name'的未知属性 - Angular 2在设置'recipe'对象之前编译了字符串插值 .Fix
我使用safe navigaton operator来保护属性路径中的空值:
Conclusion
路由中没有错误 - 这是我的应用程序的另一部分中的一个错误,它被chrome-dev工具捕获,然后需要修复以便继续编译应用程序