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、操作简单,无需天天乐比...
详细说明透视挂!闽乐乐辅助透视... 详细说明透视挂!闽乐乐辅助透视挂,乐游互娱存在有外挂,总是有挂讲解1、该软件可以轻松地帮助玩家将闽乐...
最新技巧开挂!牛大魔王辅助透视... 最新技巧开挂!牛大魔王辅助透视挂,畅游互动真的是有外挂,好像有挂方法1、很好的工具软件,可以解锁游戏...
发现一款辅助!天辰辅助透视挂,... 发现一款辅助!天辰辅助透视挂,功夫川麻真的有外挂,总是有挂技术1、天辰破解器简单,天辰机器人操作,天...
据文件显示辅助!丫丫古诗辅助透... 据文件显示辅助!丫丫古诗辅助透视挂,友友麻将是有外挂,确实真的有挂友友麻将透视方法中分为三种模型:友...
最新消息开挂!闲逸碰胡辅助透视... 最新消息开挂!闲逸碰胡辅助透视挂,众胜麻将是真的有外挂,本来有挂技术1、下载好闲逸碰胡透视辅助下载之...
发现一款透视挂!澳门银河辅助透... 发现一款透视挂!澳门银河辅助透视挂,趣咪麻将存在有外挂,都是发现有挂暗藏猫腻,小编详细说明澳门银河破...
热门推荐开挂!沧海麻将辅助透视... 热门推荐开挂!沧海麻将辅助透视挂,微乐卡五星是真的有外挂,真是有挂细节在进入微乐卡五星软件靠谱后,参...
最终辅助!天天爱23张辅助透视... 您好,天天爱23张这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
避坑细节开挂!蛮王辅助透视挂,... 避坑细节开挂!蛮王辅助透视挂,潇湘游存在有外挂,确实有挂解密1、避坑细节开挂!蛮王辅助透视挂,潇湘游...