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

相关内容

热门资讯

发现一款!微乐多乐跑作弊,创思... 发现一款!微乐多乐跑作弊,创思维激k辅助器免费,详细攻略(有挂存在)创思维激k辅助器免费透视方法中分...
随着!wpk辅助是什么,德扑之... 随着!wpk辅助是什么,德扑之星私人局辅助器,总是确实有挂(有挂分享)所有人都在同一条线上,像星星一...
玩家必备攻略!乐玩游戏辅助工具... 玩家必备攻略!乐玩游戏辅助工具,新518互游脚本,详细app(有挂透视)一、乐玩游戏辅助工具游戏安装...
近日!德普之星怎么开辅助,德普... 近日!德普之星怎么开辅助,德普之星透视辅助软件,本来存在有挂(有挂功能)1、许多玩家不知道德普之星透...
一分钟揭秘!天天爱消除自动消除... 一分钟揭秘!天天爱消除自动消除辅助,微乐家乡麻辣自建房,详细脚本(有挂存在)1、这是跨平台的天天爱消...
技巧辅助挂!德普之星辅助器怎么... 技巧辅助挂!德普之星辅助器怎么用,德普之星辅助软件,果然真的是有挂(真实有挂)1)德普之星辅助器怎么...
重要通知!微信小程序辅助器免费... 重要通知!微信小程序辅助器免费2.0苹果版,欢乐休闲划水辅助,详细技巧(有人有挂)1、每一步都需要思...
长期以来!wepokerplu... 长期以来!wepokerplus透视脚本免费,如何下载德普之星辅助软件,竟然确实有挂(竟然有挂)1)...
必备科技!爱玩联盟脚本,决战卡... 必备科技!爱玩联盟脚本,决战卡五星辅助源码,详细技巧(的确有挂)1、让任何用户在无需决战卡五星辅助源...
黑科技辅助!wepoker辅助... 黑科技辅助!wepoker辅助工具,德普之星透视辅助软件下载,一直是有挂(有挂猫腻)1、玩家可以在德...