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辅助器... 重大通报!wepoker辅助器软件下载(辅助挂)好像有挂(有挂方针)1、上手简单,内置详细流程视频教...
科普常识!德州透视脚本(辅助挂... 科普常识!德州透视脚本(辅助挂)都是真的有挂(有挂存在)1、德州透视脚本辅助器安装包、德州透视脚本辅...
解密关于!安装不了wepoke... 解密关于!安装不了wepoker(辅助挂)一直是有挂(确实有挂)1、完成安装不了wepoker有辅助...
推荐一款!如何下载wepoke... 推荐一款!如何下载wepoker安装包(辅助挂)一直真的有挂(有挂神器)1、操作简单,无需如何下载w...
实操分享!智星菠萝辅助(辅助挂... 实操分享!智星菠萝辅助(辅助挂)都是是有挂(有挂透明挂)1、许多玩家不知道智星菠萝辅助辅助怎么退出观...
玩家攻略!wepoker软件安... 玩家攻略!wepoker软件安装包(辅助挂)果然是有挂(有挂解惑)1)wepoker软件安装包免费钻...
大神推荐!德普之星怎么开辅助(... 大神推荐!德普之星怎么开辅助(辅助挂)一直是真的有挂(存在有挂)大神推荐!德普之星怎么开辅助(辅助挂...
科普攻略!来玩app破解版(辅... 科普攻略!来玩app破解版(辅助挂)本来存在有挂(竟然有挂)1、来玩app破解版有没有辅助教程、来玩...
重大通报!aapoker能控制... 重大通报!aapoker能控制牌吗(辅助挂)本来存在有挂(真是有挂)1.aapoker能控制牌吗 选...
实测必看!智星德州可以透视吗(... 您好,智星德州可以透视吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...