Angular路由器:为什么Router ActivatedRoute.children是一个数组/始终只有一个子级?
创始人
2024-10-28 04:30:15
0次

在Angular中,当使用路由器进行导航时,可以使用ActivatedRoute来访问当前路由的信息,包括路由参数、查询参数等。而ActivatedRoute对象的children属性是一个包含当前路由的子路由的数组。

通常情况下,ActivatedRoute.children数组只有一个子级,这是因为路由配置中定义了一个子路由。如果路由配置中没有定义子路由,children数组将为空。但是,ActivatedRoute.children始终是一个数组,即使只有一个子级。

以下是一个示例来解释为什么ActivatedRoute.children是一个数组/始终只有一个子级的原因:

// app.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent, children: [
    { path: 'child', component: ChildComponent }
  ]},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppModule { }

// about.component.ts
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-about',
  template: `
    

About Page

` }) export class AboutComponent { constructor(private route: ActivatedRoute) { console.log(route.children); // [ActivatedRoute] } } // child.component.ts import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-child', template: `

Child Page

` }) export class ChildComponent { constructor(private route: ActivatedRoute) { console.log(route.children); // [] } }

在上面的示例中,我们定义了一个父级路由about和一个子级路由child。当访问/about时,AboutComponent会被加载,并且route.children将包含一个ActivatedRoute对象。而当访问/about/child时,ChildComponent会被加载,并且route.children将为空数组。

通过以上示例,你可以看到ActivatedRoute.children是一个数组,即使只有一个子级。你可以通过访问route.children[0]来获取子级的ActivatedRoute对象。

相关内容

热门资讯

攻略讲解开挂!黑莓大厅开挂多功... 攻略讲解开挂!黑莓大厅开挂多功能AI教程,黑莓大厅其实有开挂教程1、黑莓大厅有没有辅助教程、黑莓大厅...
技术分享作弊器!福城娱乐作弊器... 技术分享作弊器!福城娱乐作弊器多功能AI插件,福城娱乐确实有作弊器插件1)福城娱乐免费钻石:进一步探...
每日必备外挂!蜜瓜大厅外挂多功... 每日必备外挂!蜜瓜大厅外挂多功能AIapp,蜜瓜大厅确实有外挂app1、这是跨平台的蜜瓜大厅轻量版有...
技术分享外挂!光明大厅外挂多功... 技术分享外挂!光明大厅外挂多功能AI教程,光明大厅原来是有外挂教程;1、每一步都需要思考,不同水平的...
推荐几款新版透视器!丁丁娱乐透... 推荐几款新版透视器!丁丁娱乐透视器多功能AI教程,丁丁娱乐好像是有透视器教程1、任何丁丁娱乐透视是真...
盘点一款透视挂!六六互娱透视挂... 盘点一款透视挂!六六互娱透视挂多功能AI插件,六六互娱果然存在有透视挂插件盘点一款透视挂!六六互娱透...
研究成果辅助器!新世纪辅助器多... 研究成果辅助器!新世纪辅助器多功能AI脚本,新世纪本来存在有辅助器脚本新世纪破解侠是真的助透视。每个...
今日重大通报外挂!皇豪大厅外挂... 今日重大通报外挂!皇豪大厅外挂多功能AI攻略,皇豪大厅一直真的是有外挂攻略进入游戏-大厅左侧-新手福...
必看攻略开挂!忠乐大厅开挂多功... 必看攻略开挂!忠乐大厅开挂多功能AI技巧,忠乐大厅好像是有开挂技巧1)忠乐大厅免费钻石:进一步探索忠...
玩家必看教程辅助器!甘孜大厅辅... 玩家必看教程辅助器!甘孜大厅辅助器多功能AI攻略,甘孜大厅切实是真的有辅助器攻略1、甘孜大厅有没有辅...