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

相关内容

热门资讯

WPK透视版透视挂练习!wpk... WPK透视版透视挂练习!wpk辅助购买,德扑之星ai多功能透视挂工具1)wpk辅助购买辅助插件:进一...
WPK安装透视资料!wepok... WPK安装透视资料!wepoker游戏下载,德州扑克ai多功能透视appwepoker游戏下载是不是...
WPK真假透视方式!wepok... WPK真假透视方式!wepoker辅助透视软件,wpkai多功能透视技巧1、wepoker辅助透视软...
WPK插件透视挂方针!wepo... WPK插件透视挂方针!wepoker有机器人吗,wpkai多功能透视挂脚本1、进入游戏-大厅左侧-新...
WPK多开辅助器总结!德普软件... WPK多开辅助器总结!德普软件,微扑克ai多功能辅助器神器1、每一步都需要思考,不同水平的挑战德普软...
WPK购买辅助器要领!wepo... WPK购买辅助器要领!wepoker代打辅助机器人,aapokerai多功能辅助器技巧1、起透看视 ...
WPK四人透视大纲!wepok... WPK四人透视大纲!wepoker免费脚本咨询,wpkai多功能透视插件1、完成wepoker免费脚...
WPK俱乐部辅助器讲义!wep... WPK俱乐部辅助器讲义!wepoker有透视底牌吗,德州扑克ai多功能辅助器脚本1、操作简单,无需w...
WPK模拟器透视妙招!wpk透... WPK模拟器透视妙招!wpk透视辅助下载,AApokerai多功能透视工具小薇(辅助器软件下载)致您...
WPK真假开挂要领!wpk软件... WPK真假开挂要领!wpk软件是正规的吗,红龙PoKerai多功能开挂神器1、任何wpk软件是正规的...