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

相关内容

热门资讯

技巧知识分享!有哪些免费的wp... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
终于懂了!wpk真的有透视嘛,... 终于懂了!wpk真的有透视嘛,WPK透视辅助下载(固有是有辅助器)AI 是一款可以让一直输的玩家修复...
今日重大通报!wepoker私... 今日重大通报!wepoker私局辅助,德普之星透视插件(其实真的是有辅助挂)AI 智能体黑科技再上新...
揭秘几款!wpk辅助器,微扑克... 揭秘几款!wpk辅助器,微扑克透视辅助安装(从前真的是有辅助器)AI 智能体黑科技再上新,自动化能力...
每日必看!poker辅助器免费... 每日必看!poker辅助器免费安装,德扑之星透视是真的吗工具(其实是有辅助挂)AI 是一款可以让一直...
实测必看!wepoker透视苹... wepoker透视苹果系统AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻...
避坑细节!wepoker怎么增... 您好:wepoker怎么增加运气这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
大家学习交流!WPK官网,WP... 您好,大家学习交流!WPK官网,WPK开挂技巧平台(果然有透视挂)这款游戏可以开挂的,确实是有挂的,...
分享开挂内幕!wepoker线... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
AI教程!wepoker有人用... AI教程!wepoker有人用过吗,德扑之星可以装挂吗神器(原来真的有透视)AI 是一款可以让一直输...