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

相关内容

热门资讯

科技通报!hhpoker真的有... 科技通报!hhpoker真的有透视吗(辅助挂)一直有挂(有挂讲解辅助工具);1)辅助插件:进一步探索...
一分钟快速了解!we poke... 一分钟快速了解!we poker插件(辅助挂)原来真的有挂(有挂详情辅助器)1)辅助插件:进一步探索...
免费测试版!wepoker怎么... 免费测试版!wepoker怎么增加运气(辅助挂)总是真的有挂(真的有挂辅助技巧)一、游戏安装教程牌型...
信息共享!wepoker辅助器... 信息共享!wepoker辅助器官方(辅助挂)本来有挂(有挂分享辅助方法)1、许多玩家不知道辅助怎么退...
热点讨论!wepokerplu... 热点讨论!wepokerplus外挂(辅助挂)本来真的有挂(有挂规律辅助攻略)一、可以开透视的定义与...
今日公布!wepoker怎么获... 今日公布!wepoker怎么获得好牌(辅助挂)果然真的是有挂(讲解有挂辅助脚本)脚本下载中分为三种模...
科普常识!德普之星有透视辅助吗... 科普常识!德普之星有透视辅助吗(辅助挂)切实真的是有挂(有挂实锤辅助工具)1、游戏颠覆性的策略玩法,...
推荐十款!wepoker有没有... 推荐十款!wepoker有没有透视方法(辅助挂)一贯真的有挂(讲解有挂辅助攻略)进入游戏-大厅左侧-...
技巧知识分享!拱趴大菠萝万能辅... 技巧知识分享!拱趴大菠萝万能辅助器(辅助挂)本来是有挂(有挂规律辅助软件)1、游戏颠覆性的策略玩法,...
9分钟了解!hhpoker必备... 9分钟了解!hhpoker必备开挂(辅助挂)都是真的有挂(竟然有挂辅助技巧)1、用户打开应用后不用登...