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

相关内容

热门资讯

透视科技!wepoke有辅助挂... 透视科技!wepoke有辅助挂,wepoke系统是免费的吗,详细透视细节揭秘;1、让任何用户在无需w...
德州之星辅助挂!aapoker... 德州之星辅助挂!aapoker俱乐部后台可以操作吗(透视)好像真的是有挂(详细辅助规律教程)1、不需...
透视游戏!aapoker透明挂... 透视游戏!aapoker透明挂,wepoke支持安卓吗,详细透视扑克教程1、全新机制【aapoker...
wepoke是真的有挂!云扑克... wepoke是真的有挂!云扑克辅助(透视)从前真的是有挂(详细辅助2025版教程)是一款可以让一直输...
透视有挂!wepoke辅助有挂... 透视有挂!wepoke辅助有挂,德州poker有外挂吗,详细透视透明挂教程1、wepoke辅助有挂系...
德扑之星有作弊!德州ai机器人... 德扑之星有作弊!德州ai机器人辅助(透视)一贯是有挂(详细辅助科技教程);德扑之星有作弊!德州ai机...
透视好友!wepoke有没有挂... 透视好友!wepoke有没有挂,wepoke 软件,详细透视解密教程wepoke有没有挂辅助器中分为...
德州AI智能辅助机器人!微扑克... 德州AI智能辅助机器人!微扑克辅助机器人(透视)原先存在有挂(详细辅助2025新版教程)您好,德州A...
透视挂透视!wepokeai机... 透视挂透视!wepokeai机器人,wepoke有挂吗,详细透视AI教程1、wepokeai机器人透...
智星德州菠萝偷偷看牌功能!德扑... 智星德州菠萝偷偷看牌功能!德扑ai自定义设置数据(透视)起初是真的有挂(详细辅助实用技巧)1、许多玩...