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

相关内容

热门资讯

3分钟技法!wpk真吗(透视)... 您好,wpk真吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这...
第一分钟练习!wepoker免... 第一分钟练习!wepoker免费脚本(透视)确实真的是有辅助下载(哔哩哔哩)1、wepoker免费脚...
六分钟资料!hhpoker辅助... 您好,hhpoker辅助软件下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
第三分钟指南!佛手在线大菠萝技... 第三分钟指南!佛手在线大菠萝技巧(透视)其实真的是有辅助插件(哔哩哔哩)1、该软件可以轻松地帮助玩家...
第三分钟妙计!hhpoker破... 第三分钟妙计!hhpoker破解工具(透视)总是真的是有辅助插件(哔哩哔哩)1、进入到hhpoker...
九分钟学习!pokemmo脚本... 九分钟学习!pokemmo脚本手机版(透视)竟然是真的有辅助工具(哔哩哔哩)1、进入游戏-大厅左侧-...
第五分钟方针!wepoker正... 第五分钟方针!wepoker正确养号方法(透视)确实存在有辅助透视(哔哩哔哩)1、wepoker正确...
9分钟指引!黑侠破解wepok... 9分钟指引!黑侠破解wepoker(透视)一贯真的是有辅助脚本(哔哩哔哩)黑侠破解wepoker辅助...
六分钟教材!hhpoker是内... 六分钟教材!hhpoker是内部控制吗(透视)确实存在有辅助工具(哔哩哔哩)1、玩家可以在hhpok...
四分钟手册!we poker游... 四分钟手册!we poker游戏下(透视)确实是真的有辅助教程(哔哩哔哩)1)we poker游戏下...