我目前正在使用Anuglar 2开发应用程序,并且我正在尝试将应用程序启动时路由到我的主页。
我有一个main.html和一个main.ts文件,它们自己加载并有各种嵌套视图(如果这是正确的名称)可以加载,home就是其中之一。
此时的代码如下所示:
import {[...], Router} from 'angular2/router';
[...]
@Component({
selector: 'main',
bindings: [Router]
})
@View({
directives: [[...] Router],
templateUrl: '[...]/main.html'
})
export class mainApp {
private router;
constructor(router: Router)
{
router.navigateByUrl('/home');
}
}
bootstrap(mainApp, [[...}, Router]);
[...]表示一些其他代码对于问题本身无关紧要。
现在代码存在,启动App会抛出以下错误:
无法解析函数Router(registry,parent,hostComponent){(?,?,?)的所有参数。确保它们都有有效的类型或注释。
如何解决此问题并使路由/自动导航生效?
延迟编辑: 在项目中与队友进行了一些关于更新到角度2 alpha 45的讨论......事实证明这实际上是问题背后的原因。现在整个事情都很好用我必须开始的东西(以及对导入的东西的一些调整)。
答案 0 :(得分:1)
要自动重定向,您可以像这样使用redirectTo
:
@RouteConfig([
{ path: '/', redirectTo: '/home' }
{ path: '/home', component: Home, as: 'Home' }
])
答案 1 :(得分:1)
您应该使用useAsDefault: true
设置默认路由,如下所示:
@RouteConfig([
{ path: '/home', component: Home, as: 'Home', useAsDefault: true },
{ path: '/other', component: Other, as: 'Other }
])
启动时,假设请求的路径为'/',应用程序将启动您的家庭组件。
答案 2 :(得分:0)
使用下一个代码创建Separeta路由模块文件(例如app-routing.module.ts):
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
const routes: Routes = [
{path: '', redirectTo: '/home', pathMatch: 'full'},
{path: 'home', component: HomeComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}