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

相关内容

热门资讯

九分钟教程!微乐小程序免费黑科... 您好,微乐小程序免费黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
黑科技插件!微乐小程序黑科技,... 黑科技插件!微乐小程序黑科技,微信小程序微乐内蒙破解器(透视)其实存在有挂(哔哩哔哩)1、首先打开微...
第三分钟插件!微乐小程序免费黑... 第三分钟插件!微乐小程序免费黑科技,微乐小程序辅助器出租(开挂)原来是真的挂(2026)1、任何微乐...
透视辅助!微乐小程序黑科技,微... 透视辅助!微乐小程序黑科技,微乐自建房辅助工具免费(透视)一直真的是有挂(哔哩哔哩)1、金币登录送、...
近期!微乐小程序黑科技,微乐智... 近期!微乐小程序黑科技,微乐智能辅助软件是真的吗(透视)总是真的是有挂(哔哩哔哩)微乐智能辅助软件是...
第3分钟脚本!微乐小程序黑科技... 第3分钟脚本!微乐小程序黑科技,微乐小程序破解(开挂)原来有挂(2026)1、游戏颠覆性的策略玩法,...
记者获悉!微乐小程序黑科技,微... 记者获悉!微乐小程序黑科技,微乐小程序多功能修改器(透视)其实是真的挂(哔哩哔哩);1、任何微乐小程...
第3分钟下载!微乐小程序黑科技... 第3分钟下载!微乐小程序黑科技,微乐家乡辅助app免费(开挂)真是是真的挂(2026)1、第3分钟下...
复盘辅助挂!微乐小程序免费黑科... 复盘辅助挂!微乐小程序免费黑科技,微乐陕西小程序破解器(透视)果然是有挂(哔哩哔哩)1、微乐陕西小程...
第二分钟工具!微乐小程序免费黑... 第二分钟工具!微乐小程序免费黑科技,微信小程序四川微乐脚本(开挂)都是是真的挂(2026)1、完成微...