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、边锋老友荣成辅助器破解器简...
网友热议!红龙poker辅助,... 网友热议!红龙poker辅助,hhpoker这个软件靠谱吗,方案教程(揭秘有挂)1、超多福利:超高返...
经调查!aapoker真的假的... 经调查!aapoker真的假的,赣湘互娱怎么下载辅助,演示教程(有挂规律)1、经调查!aapoker...
2026版攻略!有没有人wep... 2026版攻略!有没有人wepoker,山城九九辅助,手段教程(有挂功能)1、下载好山城九九辅助脚本...
2026版规律!wepoker... 2026版规律!wepoker私人局透视插件,楚天游辅助,操作教程(有挂规律)1、实时楚天游辅助透视...
黑科技插件!菠萝辅助器免费版的... 黑科技插件!菠萝辅助器免费版的特点,多乐游戏修改器,办法教程(讲解有挂)1、多乐游戏修改器脚本辅助下...
黑科技插件!wepoker黑侠... 黑科技插件!wepoker黑侠破解,小程序家乡大贰脚本,窍门教程(的确有挂)1、完成小程序家乡大贰脚...
教学辅助挂!佛手大菠萝辅助,微... 教学辅助挂!佛手大菠萝辅助,微乐小程序辅助器代理,技法教程(确实有挂)1、打开软件启动之后找到中间准...
连日来!wejoker手机版透... 连日来!wejoker手机版透视脚本,手机脚本辅助软件,手册教程(有挂透视)1、手机脚本辅助软件辅助...
这一问题亟待解决!德州透视脚本... 这一问题亟待解决!德州透视脚本,创思维正版辅助器下载,模块教程(有挂方针)1、金币登录送、破产送、升...