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对象。

相关内容

热门资讯

科技揭秘!情怀莆仙外挂,约局吧... 科技揭秘!情怀莆仙外挂,约局吧德州真的有透视挂吗,力荐教程(有挂猫腻);科技揭秘!情怀莆仙外挂,约局...
玩家必备科普!宝宝浙江游戏作弊... 玩家必备科普!宝宝浙江游戏作弊是真的假的,佛手大菠萝有挂吗,专业教程(有挂详情);玩家必备科普!宝宝...
分辨真假!孝感卡五星辅助,we... 分辨真假!孝感卡五星辅助,wepoker有透视吗,扑克教程(有挂辅助)是一款可以让一直输的玩家,快速...
揭秘关于!甘肃白银麻将辅助软件... 揭秘关于!甘肃白银麻将辅助软件,佛手在线大菠萝智能辅助器,可靠技巧(有挂功能);致您一封信;亲爱甘肃...
每日必看推荐!途游四川小程序脚... 每日必看推荐!途游四川小程序脚本,wepoker私人局透视方法,安装教程(有挂秘笈);详细途游四川小...
科普分享!情怀宜春辅助,wer... 科普分享!情怀宜春辅助,werplan外卦神器,扑克教程(有挂教程);情怀宜春辅助简单的灵活控制,仅...
详细说明!九九山城万州版脚本,... 详细说明!九九山城万州版脚本,wejoker免费脚本,线上教程(有挂解密)是一款可以让一直输的玩家,...
一分钟了解!奇迹掌趣辅助,wp... 一分钟了解!奇迹掌趣辅助,wpk作弊最怕三个东西,新版2025教程(有挂教程);一分钟了解!奇迹掌趣...
终于知道!花舍辅助,wejok... 终于知道!花舍辅助,wejoker透视方法,扑克教程(有挂规律);花舍辅助软件透明挂作为一款花舍辅助...
来一盘!哈局八张有没有透视挂,... 来一盘!哈局八张有没有透视挂,hhpoker有后台操控吗,解密教程(有挂规律)是一款可以让一直输的玩...