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

相关内容

热门资讯

专业透视!pokerworld... 专业透视!pokerworld修改器,微乐江苏小程序游戏破解下载,办法教程(详细教程)-哔哩哔哩1、...
详细透视!pokerworld... 详细透视!pokerworld辅助器,微乐自建房辅助工具官网,技法教程(有挂技巧)-哔哩哔哩亲,关键...
推荐透视!wepoker开脚本... 推荐透视!wepoker开脚本视频,微乐游戏竞技团辅助,指南书教程(有挂解密)-哔哩哔哩1、游戏颠覆...
开挂透视!aapoker辅助怎... 开挂透视!aapoker辅助怎么用,微乐小程序自建房辅助ios,攻略教程(有挂方略)-哔哩哔哩1、超...
曝光透视!wepoker如何设... 曝光透视!wepoker如何设置透视,微信小程序游戏破解器,攻略教程(确实有挂)-哔哩哔哩小薇(辅助...
曝光透视!epoker有透视吗... 曝光透视!epoker有透视吗,微乐手游脚本辅助,窍要教程(证实有挂)-哔哩哔哩1、epoker有透...
辅助透视!德州hhpoker脚... 辅助透视!德州hhpoker脚本,微乐自建房脚本下载,总结教程(果真有挂)-哔哩哔哩1、辅助透视!德...
普及透视!wepoker作弊方... 普及透视!wepoker作弊方法,微乐a3纸牌有脚本,模板教程(的确有挂)-哔哩哔哩亲,关键说明,w...
揭幕透视!pokerworld... 揭幕透视!pokerworld修改器,微乐小程序授权,机巧教程(有挂头条)-哔哩哔哩1、用户打开应用...
分享透视!wepoker-h5... 分享透视!wepoker-h5下载,微乐如何自己建脚本,机巧教程(有挂技巧)-哔哩哔哩1、点击下载安...