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

相关内容

热门资讯

代打辅助挂!steampoke... 代打辅助挂!steampokermaster辅助,智星菠萝可以辅助吗,其实是有挂(有挂透明挂)1、玩...
最强版pokernow辅助控制... 最强版pokernow辅助控制,wepoker好友局透视,竟然真的有挂(有挂解惑)小薇(辅助器软件下...
这一现象值得深思!wepoke... 您好,德普软件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款...
最强版aapoker辅助软件合... 最强版aapoker辅助软件合法吗,HH平台挂,竟然真的是有挂(有挂秘诀)1、用户打开应用后不用登录...
2026版教程!we-poke... 2026版教程!we-poker辅助器,德普辅助软件,都是真的是有挂(有挂助手)一、德普辅助软件游戏...
最强版hhpoker辅助靠谱吗... 最强版hhpoker辅助靠谱吗,wepoker透视是真的吗,确实真的是有挂(有挂助手)亲,关键说明,...
反观!hhpoker透视方法,... 您好,德普之星辅助工具如何打开这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
最强版约局吧德州透视,poke... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
据文件显示!aapoker辅助... 据文件显示!aapoker辅助软件合法吗,德扑之星辅助工具如何打开,好像存在有挂(有挂分析)1、超多...
最强版德州局HHpoker透视... 最强版德州局HHpoker透视脚本,hhpoker真的有透视吗,好像是有挂(有挂规律)1、起透看视 ...