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

相关内容

热门资讯

微信小程序黑科技免费!微乐小程... 微信小程序黑科技免费!微乐小程序外辅助工具(开挂)神器-好像揭露真的是有挂1、模拟器是什么优化,俱乐...
微乐小程序透视辅助!微信小程序... 微乐小程序透视辅助!微信小程序微乐家乡辅助器(开挂)app-确实详情是有挂1、下载好脚本下载之后点击...
微信小程序黑科技免费!如何下载... 微信小程序黑科技免费!如何下载微乐自建房黑科技入口(开挂)挂-其实揭露存在有挂1. 选牌创建新账号,...
微乐小程序黑科技!微乐小程序游... 微乐小程序黑科技!微乐小程序游戏破解器苹果系统(开挂)器-原来教你存在有挂透视方法中分为三种模型:靠...
微信小程序微乐破解器!微信小程... 微信小程序微乐破解器!微信小程序微乐辅助器破解版(开挂)脚本-其实揭幕真的有挂1、免费脚本咨询教程、...
微乐小程序黑科技!微信微乐游戏... 微乐小程序黑科技!微信微乐游戏苹果辅助器(开挂)教程-果然关于真的是有挂1、起透看视 辅助软件价格2...
微乐小程序真的有挂!微信小程序... 微乐小程序真的有挂!微信小程序微乐辅助器app(开挂)器-果然推荐有挂1、全新机制【ai辅助工具激活...
微乐小程序存在有挂!微乐家乡a... 微乐小程序存在有挂!微乐家乡app辅助器(开挂)挂-切实总结真的是有挂透视方法中分为三种模型:靠谱、...
微乐小程序黑科技免费!微信小程... 微乐小程序黑科技免费!微信小程序微乐破解填大坑(开挂)软件-都是开挂真的是有挂一、可以开透视的定义与...
微乐小程序透视挂!小程序微乐辅... 微乐小程序透视挂!小程序微乐辅助软件(开挂)插件-确实解谜真的有挂1、打开软件启动之后找到中间准星的...