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、打开软件启动之后找到中间准星的标志长按。...
玩家必看分享!微信小程序微乐辅... 您好,微信小程序微乐辅助器教程这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
每日必看教程!四川血战到底辅助... 您好,四川血战到底辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
推荐一款!微信小程序辅助器免费... 推荐一款!微信小程序辅助器免费2.0苹果版,欢乐休闲划水辅助(果然真的是有挂)微信小程序辅助器免费2...
实测揭晓!唯思竞技游戏辅助,a... 实测揭晓!唯思竞技游戏辅助,aa poker辅助包,第三方教程(有挂解惑);1、很好的唯思竞技游戏辅...
推荐十款!微信边锋辅助挂件,w... 推荐十款!微信边锋辅助挂件,wepoker私人局辅助器(原来是真的有挂)1)wepoker私人局辅助...
玩家必备科技!微信多乐跑胡子作... 《玩家必备科技!微信多乐跑胡子作弊,hhpoker底牌透视脚本,可靠技巧(有挂技巧)》 微信多乐跑胡...
我来教教大家!宝宝浙江辅助脚本... 我来教教大家!宝宝浙江辅助脚本,哈糖大菠萝有没有挂,技巧教程(有挂讲解);大家肯定在之前宝宝浙江辅助...
终于清楚!乐达app辅助,三哥... 终于清楚!乐达app辅助,三哥玩摆头挂(果然是有挂)1、点击下载安装,三哥玩摆头挂脚本分类一目了然!...
热点讨论!内蒙博乐填大坑辅助,... 热点讨论!内蒙博乐填大坑辅助,hhpoker有没有作弊辅助,技巧教程(有挂教程);1、内蒙博乐填大坑...