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

相关内容

热门资讯

2分钟细说“wepoker开挂... >>您好:wepoker开挂辅助方法确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
盘点几款“wpk辅助挂”开挂辅... 盘点几款“wpk辅助挂”开挂辅助器(透视)力荐教程是一款可以让一直输的玩家,快速成为一个“必胜”的a...
热点推荐“wepoker能不能... wepoker能不能开挂是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可...
最新技巧“wepokerpus... 无需打开直接搜索;操作使用教程:最新技巧“wepokerpus透视挂是真的假的”开挂辅助软件(透视)...
科技介绍“wepoker透视软... wepoker透视软件挂教程是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用...
终于清楚“wePoKer有透视... >>您好:wePoKer有透视软件吗软件加扣扣群确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
科技通报“wepoker能不能... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
传递经验“微扑克透牌”开挂辅助... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
一分钟带你了解“微扑克发牌规律... >>您好:微扑克发牌规律软件加扣扣群确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
一起来探讨“wepoker机制... 您好:wepoker机制发冤家牌这款游戏是可以开挂的,软件加【添加微信客服136704302】确实是...