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

相关内容

热门资讯

玩家必看科普!白金岛麻将圈辅助... 玩家必看科普!白金岛麻将圈辅助脚本软件,白金岛麻将圈竟然是真的有辅助解密方法运白金岛麻将圈辅助工具,...
一分钟了解!柳州红中麻将透视挂... 您好,柳州红中麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
发现玩家!嘻游联盟辅助器脚本软... 发现玩家!嘻游联盟辅助器脚本软件,嘻游联盟好像是有辅助器辅助app1、嘻游联盟透视辅助软件激活码多个...
如何分辨真伪!沅江麻将透视脚本... 如何分辨真伪!沅江麻将透视脚本软件,沅江麻将一直存在有透视科普app1、下载好沅江麻将脚本下载之后点...
教学盘点!闲逸碰胡辅助脚本软件... 教学盘点!闲逸碰胡辅助脚本软件,闲逸碰胡本来是有辅助解迷教程进入游戏-大厅左侧-新手福利-激活码辅助...
实测教程!丫丫陕西麻将透视脚本... 实测教程!丫丫陕西麻将透视脚本软件,丫丫陕西麻将一直是真的有透视有挂技巧1、玩家可以在丫丫陕西麻将透...
新手必备!喜乐透视挂脚本软件,... 新手必备!喜乐透视挂脚本软件,喜乐其实是真的有透视挂普及脚本喜乐透视方法中分为三种模型:喜乐靠谱、喜...
我来教教大家!天天贵阳辅助器脚... 我来教教大家!天天贵阳辅助器脚本软件,天天贵阳好像有辅助器了解app亲,关键说明,天天贵阳透视脚本安...
重大通报!边锋老友内蒙古麻将透... 重大通报!边锋老友内蒙古麻将透视脚本软件,边锋老友内蒙古麻将真是是真的有透视详情攻略1、边锋老友内蒙...
最新技巧!天天爱海南麻将开挂脚... 最新技巧!天天爱海南麻将开挂脚本软件,天天爱海南麻将好像有开挂详细教程1、该软件可以轻松地帮助玩家将...