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)心悦辽宁麻将辅助插件...
一分钟揭秘辅助!欢乐龙城3辅助... 一分钟揭秘辅助!欢乐龙城3辅助透视挂,同城花牌是有外挂,确实有挂神器1、欢乐龙城3辅助软件下载优化,...
揭秘真相开挂!白银岛辅助透视挂... 揭秘真相开挂!白银岛辅助透视挂,九九互娱是真的有外挂,其实有挂助手1、每一步都需要思考,不同水平的挑...
攻略讲解辅助!微乐广西麻将辅助... 攻略讲解辅助!微乐广西麻将辅助透视挂,边锋老友宁安麻将确实有外挂,一直有挂方针1、边锋老友宁安麻将辅...
2分钟细说辅助!爱玩辽宁麻将辅... 2分钟细说辅助!爱玩辽宁麻将辅助透视挂,传奇游戏休闲是真的有外挂,一贯有挂方法1、上手简单,内置详细...
终于清楚辅助!天龙座大厅辅助透... 终于清楚辅助!天龙座大厅辅助透视挂,天天游戏是有外挂,好像有挂教程1)天龙座大厅辅助插件:进一步探索...
揭秘攻略开挂!天天休闲辅助透视... 揭秘攻略开挂!天天休闲辅助透视挂,雀友会2广东潮汕麻将是有外挂,真是有挂详情1、操作简单,无需雀友会...
据文件显示辅助!纳祥游戏辅助透... 据文件显示辅助!纳祥游戏辅助透视挂,福州麻将是有外挂,好像有挂辅助1、下载好纳祥游戏透视辅助下载之后...
无独有偶辅助!哈哈乐辅助透视挂... 无独有偶辅助!哈哈乐辅助透视挂,中至余干麻将确实有外挂,都是有挂头条1、下载好中至余干麻将脚本下载之...