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、点击下载安装,we...
据了解!wepoker透视脚本... 据了解!wepoker透视脚本免费使用视频(透视)一贯真的是有辅助软件(有挂分析)-哔哩哔哩;1、让...
透视实锤!hhpoker德州透... 透视实锤!hhpoker德州透视挂(透视)都是真的有辅助神器(有挂教程)-哔哩哔哩1、hhpoker...
刚刚!wpk有辅助器吗(透视)... 刚刚!wpk有辅助器吗(透视)好像有辅助工具(有挂功能)-哔哩哔哩;1、进入到wpk有辅助器吗是否有...
网友热议!菠萝辅助器免费版的功... 网友热议!菠萝辅助器免费版的功能介绍(透视)切实真的有辅助插件(有挂方法)-哔哩哔哩网友热议!菠萝辅...
刚刚!hhpoker怎么破解(... 刚刚!hhpoker怎么破解(透视)真是存在有辅助app(有挂解惑)-哔哩哔哩hhpoker怎么破解...
不少玩家反映!哈糖大菠萝有没有... 不少玩家反映!哈糖大菠萝有没有挂(透视)一贯是有辅助软件(有挂秘籍)-哔哩哔哩1、下载好哈糖大菠萝有...
据文件显示!wepoker插件... 据文件显示!wepoker插件功能辅助器(透视)一贯是真的辅助辅助器(竟然有挂)-哔哩哔哩1、打开软...
现有关情况通报如下!购买的wp... 您好,购买的wpk辅助在哪里下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
透视透视挂!xpoker辅助(... 透视透视挂!xpoker辅助(透视)竟然有辅助下载(有挂总结)-哔哩哔哩1、该软件可以轻松地帮助玩家...