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 服务来解决问题了。

相关内容

热门资讯

攻略讲解,德扑之星辅助作弊挂,... 攻略讲解,德扑之星辅助作弊挂,AApoker开挂破解窍要(本来真的有辅助器)AI 是一款可以让一直输...
总算明白!,wepoker透视... 总算明白!,wepoker透视辅助挂有游戏亮点,菠萝智星德州是如何开挂的窍门(先前存在有透视)AI ...
攻略讲解,wepoker辅助器... 攻略讲解,wepoker辅助器免费下载,菠萝智星德州究竟有没有挂窍要(起初真的有辅助器)是一款可以让...
分享给玩家,wepoker作弊... 您好:wepoker作弊软件是不是真的这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会...
重大通报,德州辅助nzt有用吗... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
攻略讲解,wepoker线上发... 您好:wepoker线上发牌的规律这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现...
每日必备,wepoker线上发... 每日必备,wepoker线上发牌的规律,德扑之星到底有挂吗指南书(先前是真的有开挂)是一款可以让一直...
玩家必看科普!,微扑克辅助器有... 您好,微扑克辅助器有用吗这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家...
查到实测,WePoKer有没有... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
实用技巧,德扑之星能不能透视,... 实用技巧,德扑之星能不能透视,WOK有没有透视挂举措(往昔是有透视挂)是一款可以让一直输的玩家,快速...