AngularRouter:使用带有参数的loadChildren无法传递参数问题。
创始人
2024-10-29 06:00:59
0次

在Angular中,我们可以使用路由器导航到不同的组件或文件。路由器导航通常将参数传递给组件。loadChildren 是一个在 Angular 路由器中使用的函数,可以将懒加载模块加载到应用程序中,并在该模块中注册组件。

然而,在使用 loadChildren 函数时,无法直接传递参数。这样会导致在接收参数时出现问题。这时候我们需要通过一个针对该问题的修改来解决。

首先,我们可以将懒加载模块的路由制成根路径,如下:

const appRoutes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'users/:id', loadChildren: () => import('./user/user.module').then(m => m.UserModule) },
];

然后我们需要在模块中使用路径路径来接收参数。在模块中,我们使用 forChild 函数来定义路由。如下:

const userRoutes: Routes = [
  {
    path: '',
    component: UserComponent,
    children: [
      { path: '', component: UserListComponent },
      { path: 'add', component: UserAddComponent },
      { path: ':id', component: UserDetailComponent },
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(userRoutes)],
  exports: [RouterModule]
})
export class UserRoutingModule { }

接下来我们可以在组件中通过 ActivatedRoute 来获取参数。ActivatedRoute 是 Angular 路由器中的一个服务,用于监控和获取当前路由。

例如,我们可以在 UserDetailComponent 组件中获取参数,如下:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {
  userId: any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.userId = params['id'];
    });
  }
}

这样就可以通过 loadChildren 函数和 ActivatedRoute 服务来解决问题了。

相关内容

热门资讯

WPK模拟器!红龙扑克软件辅助... WPK模拟器!红龙扑克软件辅助器ai,哈糖大菠萝可以开挂吗,切实是有ai辅助器窍要1、首先打开哈糖大...
WPK真假!aapoker技巧... WPK真假!aapoker技巧辅助ai,wpk私人局辅助是真的吗,竟然真的是有ai辅助举措所有人都在...
WPK方法!菠萝智星德州app... WPK方法!菠萝智星德州app透视挂ai,AApoker辅助工具,切实是有ai透视挂方针小薇(辅助器...
WPK四人!WePoKer软件... WPK四人!WePoKer软件辅助器ai,aapoker公共底牌,原来有ai辅助器手册1、上手简单,...
WPK脚本!红龙扑克工具辅助器... WPK脚本!红龙扑克工具辅助器ai,佛手在线是不是有挂,一直存在有ai辅助器总结1)佛手在线是不是有...
WPK软件!菠萝智星德州攻略透... WPK软件!菠萝智星德州攻略透视ai,AApoker方法,一贯真的有ai透视操作1、玩家可以在AAp...
WPK方法!wpk插件透视挂a... WPK方法!wpk插件透视挂ai,红龙poker辅助器免费观看,好像是真的有ai透视挂讲义;红龙po...
WPK作弊!德州扑克软件辅助a... WPK作弊!德州扑克软件辅助ai,佛手大菠萝13道挂哪里,总是有ai辅助方案1、超多福利:超高返利,...
WPK下载!德扑之星技巧辅助a... WPK下载!德扑之星技巧辅助ai,wpk作弊是真的吗,原来有ai辅助机巧wpk作弊是真的吗脚本下载中...
WPK私人局!智星菠萝德州脚本... WPK私人局!智星菠萝德州脚本透视ai,德普之星透视辅助插件,真是有ai透视策略WPK私人局!智星菠...