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

相关内容

热门资讯

透视解谜"aapok... 透视解谜"aapoker真的假的"一贯存在有辅助方法(哔哩哔哩)1、打开软件启动之后找到中间准星的标...
透视开挂"wpk是真... 透视开挂"wpk是真的还是假的"原来存在有辅助技巧(哔哩哔哩)1、起透看视 wpk是真的还是假的辅助...
透视推荐"wepok... 透视推荐"wepoker透视有用吗"好像有辅助攻略(哔哩哔哩)1、起透看视 wepoker透视有用吗...
透视解密"wepok... 透视解密"wepoker有没有机器人"总是存在有辅助app(哔哩哔哩)亲,关键说明,wepoker有...
为了进一步!广西优乐免费辅助,... 为了进一步!广西优乐免费辅助,pokernow辅助控制(透视)原来有辅助工具(哔哩哔哩)1、为了进一...
透视总结"sohoo... 透视总结"sohoo竞技联盟辅助器"确实真的是有辅助方法(哔哩哔哩)1、许多玩家不知道sohoo竞技...
有了最新消息!微信微乐小程序辅... 有了最新消息!微信微乐小程序辅助器免费安装,wepoker怎么看底牌(透视)原来是有辅助攻略(哔哩哔...
透视辅助"wepok... 透视辅助"wepoker有辅助器吗"果然是真的辅助工具(哔哩哔哩)1、每一步都需要思考,不同水平的挑...
今天上午!边锋游戏小程序辅助器... 今天上午!边锋游戏小程序辅助器免费,wepoker辅助分析器(透视)原来是真的有辅助软件(哔哩哔哩)...
透视透视"约局吧如何... 透视透视"约局吧如何查看是否有挂"本来真的有辅助器(哔哩哔哩)1、约局吧如何查看是否有挂辅助软件下载...