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、下载好新九哥辅助脚本下载之后点击打开,先需...
七分钟辅助!沧海十三水辅助器,... 七分钟辅助!沧海十三水辅助器,其实真的有辅助器(有挂猫腻)1、任何沧海十三水辅助器透视是真的假的的玩...
9分钟辅助!心悦踢坑神器软件下... 9分钟辅助!心悦踢坑神器软件下载,都是真的是有辅助脚本(有挂透明挂)小薇(辅助器软件下载)致您一封信...
第三分钟辅助!功夫川麻老是输什... 第三分钟辅助!功夫川麻老是输什么情况,其实真的是有辅助攻略(有挂分享)1、功夫川麻老是输什么情况免费...
6分钟辅助!大当家辅助脚本设置... 6分钟辅助!大当家辅助脚本设置,切实是真的有辅助神器(有挂助手)1)大当家辅助脚本设置辅助插件:进一...
5分钟辅助!人人燕赵辅助下载,... 5分钟辅助!人人燕赵辅助下载,确实是真的有辅助技巧(竟然有挂)1、5分钟辅助!人人燕赵辅助下载,确实...
第1分钟辅助!微信小程序蜀山四... 第1分钟辅助!微信小程序蜀山四川脚本制作,确实是真的有辅助器(有挂技巧)1、微信小程序蜀山四川脚本制...
2分钟辅助!创思维激k辅助,其... 2分钟辅助!创思维激k辅助,其实是真的有辅助器(有挂攻略)1、玩家可以在创思维激k辅助线上大神俱乐部...
第2分钟辅助!智星菠萝透视,一... 第2分钟辅助!智星菠萝透视,一直是有辅助技巧(有挂总结)所有人都在同一条线上,像星星一样排成一排,每...
八分钟辅助!广东雀神胜率修改,... 八分钟辅助!广东雀神胜率修改,确实有辅助插件(存在有挂)1、点击下载安装,广东雀神胜率修改脚本分类一...