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

相关内容

热门资讯

黑科技辅助!aapoker外挂... 您好:AAPoKer记牌器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
黑科技辅助!wepoke一定有... 黑科技辅助!wepoke一定有挂,(WePoKe好友)原来真的有挂,切实教程(有挂解惑)-哔哩哔哩;...
黑科技辅助!wepower辅助... 黑科技辅助!wepower辅助器,(WePoKe美元局)原来真的有挂,AA德州教程(有挂详细)-哔哩...
黑科技辅助!wepower辅助... 黑科技辅助!wepower辅助器,(WePoKe方法)原来真的有挂,高科技教程(存在有挂)-哔哩哔哩...
黑科技辅助!悟空黑桃a辅助,(... 黑科技辅助!悟空黑桃a辅助,(悟空黑桃a辅助软件)原来真的有挂,详细教程(详细教程)-哔哩哔哩;黑科...
黑科技辅助!wepokeai代... 黑科技辅助!wepokeai代打逻辑,(WePoKe诀窍)原来真的有挂,详细教程(有挂教程)-哔哩哔...
黑科技辅助!aapoker辅助... 黑科技辅助!aapoker辅助,(AAPoKer黑科技)原来真的有挂,解密教程(竟然)-哔哩哔哩;是...
黑科技辅助!wepoke计算辅... 黑科技辅助!wepoke计算辅助,(WePoKeai机器人)原来真的有挂,技巧教程(证实有挂)-哔哩...
黑科技辅助!德扑ai智能工具,... 黑科技辅助!德扑ai智能工具,(德扑ai俱乐部)原来真的有挂,2025新版总结(助手)-哔哩哔哩,德...
黑科技辅助!悟空黑桃a免费赛,... 黑科技辅助!悟空黑桃a免费赛,(悟空德州app)原来真的有挂,实用技巧(神器)-哔哩哔哩;悟空黑桃a...