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

相关内容

热门资讯

透视好友房!哈糖大菠萝有挂吗,... 透视好友房!哈糖大菠萝有挂吗,wepoker模拟器哪个,黑科技教程(有挂详情)1、完成哈糖大菠萝有挂...
透视真的!wpk真吗,hh p... 透视真的!wpk真吗,hh poker辅助有用吗,教你攻略(有挂秘籍)1、在hh poker辅助有用...
透视规律!hhpoker德州作... 透视规律!hhpoker德州作弊,hhpoker是内部控制吗,我来教教你(有挂教程)1、很好的工具软...
透视了解!hhpoker德州挂... 透视了解!hhpoker德州挂真的有吗,wepoker祈福有用吗,2025新版(有挂教程)1、点击下...
透视计算!uupoker透视,... 透视计算!uupoker透视,拱趴大菠萝机器人,规律教程(有挂内幕)1、下载好拱趴大菠萝机器人辅助软...
透视规律!wepoker提高好... 透视规律!wepoker提高好牌率,德州私人局怎么透视,玩家教你(有挂技巧)1、进入到德州私人局怎么...
透视黑科技!wejoker辅助... 透视黑科技!wejoker辅助脚本,we poker辅助器下载,必赢教程(有挂秘籍);1、we po...
透视能赢!wepoker免费脚... 透视能赢!wepoker免费脚本咨询,hhpoker真的假的,辅助教程(有挂秘籍);1、构建自己的w...
透视教程!pokemmo辅助脚... 透视教程!pokemmo辅助脚本,hhpoker真的假的,软件教程(有挂教程)1、很好的工具软件,可...
透视教学!wejoker辅助机... 透视教学!wejoker辅助机器人,wepoker怎么看牌型,2025版教程(有挂教程)1)wepo...