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)切实是真的有挂,德州教程(有挂透视);在进入德...
黑科技辅助挂!(红龙扑克)一直... 黑科技辅助挂!(红龙扑克)一直是真的有挂,(红龙扑克)都是真的有挂,技巧教程(有挂黑科技)红龙扑克是...
黑科技辅助挂!德州aapoke... 黑科技辅助挂!德州aapoker透明挂透视辅助,(AApOKER)详细辅助wpk教程(有挂插件)亲,...
黑科技辅助挂!德州nzt辅助工... 黑科技辅助挂!德州nzt辅助工具,德州nzt软件,可靠技巧(有挂助手)运德州nzt辅助工具,进入游戏...
黑科技辅助挂!wepOke透明... 黑科技辅助挂!wepOke透明挂黑科技设备,(wepoKe)好像存在有挂,普及教程(有挂教程);1、...
黑科技辅助!wePOKE透明挂... 黑科技辅助!wePOKE透明挂黑科技功能,(WePoKer)其实存在有挂,分享教程(有挂黑科技)1、...
黑科技辅助挂!wpK透视辅助,... 黑科技辅助挂!wpK透视辅助,wpK透视有伙牌,微扑克教程(有挂黑科技);1.微扑克 ai辅助创建新...
黑科技辅助挂!智星德州菠萝辅助... 黑科技辅助挂!智星德州菠萝辅助器工具,智星德州外挂,wpk教程(有挂功能)黑科技辅助挂!智星德州菠萝...
黑科技辅助挂!AAPOKeR透... 黑科技辅助挂!AAPOKeR透明挂有假,(AaPOKER)详细辅助AI教程(有挂透明挂)1、AAPO...
黑科技辅助挂!aApoker透... 黑科技辅助挂!aApoker透明挂有内部好嘛,(AApOKER)切实真的是有挂,科技教程(有挂工具)...