我的组件显示了,但加载页面时收到错误消息。在查看了一堆资源后,我似乎根本无法解决该错误消息。
异常:错误:未捕获(承诺):无法匹配任何路由。当前段:“index.html”。可用路线:['/login']。
main.component.ts位于index.html中,页面加载后就会显示上述错误消息。
import { Component } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router';
import { LoginComponent } from './login/login.component';
@Component({
selector: 'main-component',
template:
' <header>
<h1>Budget Calculator</h1>
<a id='login' [routerLink]="['/login']">Login</a>
<router-outlet></router-outlet>
</header> '
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS]
})
@Routes([
{path: '/login', component: LoginComponent}
])
export class MainComponent {}
login.component.ts 通过 main.component.ts 路由,并且当我单击链接时确实显示,尽管有错误消息。现在,我将其样式设置为在 main.component 中的其他元素上弹出,但希望它成为页面上显示的唯一组件。如果可能的话,基本上将index.html中的main.component替换为login.component,而不是执行一大堆样式来显示:none。
import { Component } from '@angular/core';
@Component({
selector: 'login',
template:
' <div id="login-pop-up">
<h6 class="header_title">Login</h6>
<div class="login-body">
Some fancy login stuff goes here
</div>
</div> '
})
export class LoginComponent {}
还要确保您在 <base href="/">
标签开头有一个
<head>
标签或由 boostrap(...)
提供,如 Angular 2 路由器无基本 href 设置中所述
/
的路由,您可能需要让应用程序强制导航到初始路由,如 Angular2 路由器 (@angular/router) 中所述,如何设置默认路由?提示:
@angular/router
路由器也已被弃用为@angular/router-deprecated
,并且将再次发货新路由器:-/如果您打算切换到@angular/router
,最好推迟到新的、希望是最终的路由器可用。
如果您有子组件并且想要导航,请使用这种方式
路由器服务
const routes: Routes = [
{
path: '',
component: LoginComponent
},
{
path: 'home',
component: HomeComponent,
children: [
{
path: 'enter',
component: EnterDetailsComponent,
},
{
path: 'find',
component: FindDetailsComponent,
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
这样使用navigate([])方法
组件构造函数
这就是 this._router 的来历
constructor( private _router: Router) {}
this._router.navigate(['/home/find']);
当我遇到这个问题时,我通常会添加
<base href="./">
到html文件的
<head> <base href="./"> </head>
。
然后在 NG2 中导入任何文件时
import { Auth } from './auth.service';
这是根据文档进行基础操作的首选方法,
请确保您的 head 标签中有
<base href="/">
标签,您可以像这样使用 useAsDefault: true
attr :
@Routes([
{path: '/login', component: LoginComponent,useAsDefault: true}
])
只需为“”添加一条路线,例外就会消失。
{
path: '',
component: HomeComponent
}