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

相关内容

热门资讯

一分钟了解!土豪联盟辅助器,哈... 一分钟了解!土豪联盟辅助器,哈糖大菠萝免费辅助器,详细软件(有挂方略)1、上手简单,内置详细流程视频...
揭秘!老k麻将辅助器,福建天天... 揭秘!老k麻将辅助器,福建天天开心辅助真实性,详细挂(有挂实锤)福建天天开心辅助真实性透视方法中分为...
总算了解!极速猜一猜辅助,宝宝... 总算了解!极速猜一猜辅助,宝宝浙江游戏作弊是真的假的,详细攻略(有挂方略)1、宝宝浙江游戏作弊是真的...
一分钟快速了解!新道游app辅... 一分钟快速了解!新道游app辅助器,哈局辅助作弊,详细方法(有挂方针)1、任何新道游app辅助器透视...
带你了解!凑一桌游戏关春天辅助... 带你了解!凑一桌游戏关春天辅助,湖北逍遥辅助,详细攻略(有挂规律)1、很好的工具软件,可以解锁游戏的...
重大来袭!广丰中至510k辅助... 重大来袭!广丰中至510k辅助,决战辅助软件,详细攻略(有挂教学)1、实时广丰中至510k辅助透视辅...
玩家科普!微信小程序填大坑辅助... 玩家科普!微信小程序填大坑辅助器,途游四川小程序好运卡,详细脚本(有挂技巧)在进入微信小程序填大坑辅...
热点推荐!皇豪辅助,邯郸胡乐挂... 热点推荐!皇豪辅助,邯郸胡乐挂辅助,详细app(了解有挂)1、许多玩家不知道邯郸胡乐挂辅助辅助怎么退...
科普攻略!雀友会钻石辅助器潮汕... 科普攻略!雀友会钻石辅助器潮汕麻将,川南久久辅助,详细插件(有挂攻略)1)雀友会钻石辅助器潮汕麻将辅...
玩家交流!山西扣点点辅助挂定制... 玩家交流!山西扣点点辅助挂定制交易平台,微信小程序多乐辅助器,详细教程(有挂实锤)进入游戏-大厅左侧...