关于在组件中以编程方式进行路由导航,我有一个模糊的问题 . 我真的搜索了很多有用的解决方案,但我没有成为角度专家,因为我还在学习 .
简而言之 . 我有一个AppRoutingModule:
....
export const routes: Routes = [
{
path: '',
redirectTo: 'search',
pathMatch: 'full'
},
{
path: 'search',
component: SearchComponent,
children: [
{
path: 'allgarchiv',
component: AllgarchivComponent,
outlet: 'search'
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
总之,我有两个路由器出口,主要的一个和一个称为“搜索”(s . 上面) .
在加载SearchComponent(有效!)期间,我想自动路由到路径"allgarchiv"(s . above; router-outlet = "search") .
import { AfterContentInit, AfterViewInit, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'axa-search',
template: `
<br>
<ngb-tabset>
<ngb-tab title="Suche" id="tab-search">
<ng-template ngbTabContent>
<!-- <a [routerLink]="[{ outlets: { search: ['allgarchiv'] } }]">Test_LoadRouter</a> -->
<router-outlet name="search"></router-outlet>
</ng-template>
</ngb-tab>
<ngb-tab id="tab-list" [disabled]="false" title="Treffer">
<ng-template ngbTabContent>TO FILL!!!</p>
</ng-template>
</ngb-tab>
</ngb-tabset>
`,
styles: []
})
export class SearchComponent implements AfterContentInit {
constructor(private router: Router, private route: ActivatedRoute) { }
ngAfterContentInit() {
// this.router.navigate( ['allgarchiv', { outlets: { search: { relativeTo: this.route }}}] );
this.router.navigate( [{ outlets: { search: ['allgarchiv']}}] );
}
}
但这不起作用 . 我收到以下错误:
ERROR错误:未捕获(在承诺中):错误:无法匹配任何路由 . 网址段:'allgarchiv'错误:无法匹配任何路由 . 网址细分:'allgarchiv'
如果您在模板中查看,我也尝试通过首先单击Router-Link(Test_LoadRouter;当前注释) . 这就像一个魅力!
我的问题是如何从SearchComponent以编程方式导航到路由器?
我也尝试了不同的生命周期钩子,但没有任何结果和相同的错误 .
任何帮助都非常感谢 . 提前谢谢了 .
1 回答
根据您的问题,我理解的是您想要路由到特定的子组件 - onload . 请尝试以下代码:
}];
如果您只需要加载
AllgarchivComponent
,则无需在path
中指定'allgarchiv'
. 如果要使用url'search/allgarchiv'
加载页面,则只需在path
中指定'allgarchiv'
. 希望这可以帮助 .注意:使用上面的代码,您不必在
search component
中给出任何路由器导航(如ngAfterContentInit()
中所做的那样)以初始加载AllgarchivComponent
.