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、首先打开微乐自建房...
热门推荐!微乐小程序插件免费(... 热门推荐!微乐小程序插件免费(透视器),微乐安徽麻将一直是有透视挂app在进入微乐小程序插件免费软件...
实测揭晓!微信小程序微乐辅助器... 实测揭晓!微信小程序微乐辅助器破解版(开挂),微乐提坑竟然有透视挂脚本1、超多福利:超高返利,海量正...
必备辅助推荐!微乐家乡破解版(... 必备辅助推荐!微乐家乡破解版(开挂),微乐长春麻将本来真的是有透视挂软件1、这是跨平台的微乐家乡破解...
程序员教你!微乐广西麻辣(作弊... 程序员教你!微乐广西麻辣(作弊器),微乐长沙跑胡子都是真的是有透视挂攻略微乐广西麻辣透视方法中分为三...
一分钟快速了解!小程序微乐斗地... 一分钟快速了解!小程序微乐斗地主辅助(透视挂),微乐保皇一直真的是有透视挂方法1)小程序微乐斗地主辅...
重大消息!微乐家乡游戏攻略(透... 重大消息!微乐家乡游戏攻略(透视挂),陕西微乐三代切实是有透视挂软件1、微乐家乡游戏攻略脚本辅助下载...