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

相关内容

热门资讯

透视了解!竞技联盟透视插件(透... 透视了解!竞技联盟透视插件(透视)一贯真的是有挂(详细辅助2025新版);1、全新机制【软件透明挂】...
透视玄学!wepoker可以开... 透视玄学!wepoker可以开透视吗(透视)其实是真的有挂(详细辅助规律教程)软件透明挂微扑克wpk...
透视软件!淘宝买wepoker... 透视软件!淘宝买wepoker透视有用吗(透视)本来真的是有挂(详细辅助专业教程);暗藏猫腻,小编详...
透视玄学!hh poker软件... 透视玄学!hh poker软件(透视)真是真的是有挂(详细辅助实用技巧);1、系统规律教程、辅助透视...
透视科技!大菠萝789辅助器下... 透视科技!大菠萝789辅助器下载(透视)一贯存在有挂(详细辅助安装教程)1、玩家可以在软件透明挂俱乐...
透视工具!pokerrrr2辅... 透视工具!pokerrrr2辅助(透视)原来真的是有挂(详细辅助力荐教程)1、不需要AI权限,帮助你...
透视脚本!pokemmo手机版... 透视脚本!pokemmo手机版脚本免费(透视)果然存在有挂(详细辅助线上教程);1、系统规律教程、辅...
透视教学!wpk俱乐部辅助器(... 透视教学!wpk俱乐部辅助器(透视)切实真的有挂(详细辅助黑科技教程);1、该软件可以轻松地帮助玩家...
透视辅助!wepoker透视有... 透视辅助!wepoker透视有没有(透视)其实真的有挂(详细辅助新版2025教程)亲,关键说明,we...
透视总结!哈糖大菠萝有挂吗(透... 透视总结!哈糖大菠萝有挂吗(透视)切实是真的有挂(详细辅助细节方法)辅助器中分为三种模型:软件透明挂...