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

相关内容

热门资讯

WPK透视版举措!德扑圈透视挂... WPK透视版举措!德扑圈透视挂,菠萝智星德州ai多功能辅助软件1、德扑圈透视挂免费脚本咨询教程、德扑...
正版作弊器福气游戏作弊器多功能... 正版作弊器福气游戏作弊器多功能AI方法,福气游戏果然真的有作弊器方法1、用户打开应用后不用登录就可以...
WPK作弊方式!哈糖大菠萝怎么... WPK作弊方式!哈糖大菠萝怎么开挂,德州扑克ai多功能开挂插件WPK作弊方式!哈糖大菠萝怎么开挂,德...
正版辅助西元红河棋牌辅助多功能... 正版辅助西元红河棋牌辅助多功能AI插件,西元红河棋牌确实存在有辅助插件1、实时西元红河棋牌透视辅助更...
WPK安卓方针!约局吧德州真的... WPK安卓方针!约局吧德州真的有透视挂吗,WePoKerai多功能辅助器工具约局吧德州真的有透视挂吗...
正版辅助未央辅助多功能AIap... 正版辅助未央辅助多功能AIapp,未央好像存在有辅助app;1、每一步都需要思考,不同水平的挑战会更...
正版开挂王者棋牌开挂多功能AI... 正版开挂王者棋牌开挂多功能AI技巧,王者棋牌果然有开挂技巧1、下载好王者棋牌正确养号方法之后点击打开...
WPK辅助器经验!哈糖大菠萝免... WPK辅助器经验!哈糖大菠萝免费辅助器,wpkai多功能辅助神器1、完成哈糖大菠萝免费辅助器有辅助插...
正版作弊器掌心麻将圈作弊器多功... 正版作弊器掌心麻将圈作弊器多功能AIapp,掌心麻将圈切实存在有作弊器app1、金币登录送、破产送、...
WPK透视版法门!AApoke... WPK透视版法门!AApoker中牌率,微扑克ai多功能辅助技巧1、AApoker中牌率公共底牌简单...