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

相关内容

热门资讯

9分钟了解!抚州辅助器中至小程... 9分钟了解!抚州辅助器中至小程序!果然一直总是有辅助工具(真的有挂)-哔哩哔哩9分钟了解!抚州辅助器...
4分钟了解!pokemmo手机... 4分钟了解!pokemmo手机版修改器!原来一直总是有辅助技巧(的确有挂)-哔哩哔哩1、全新机制【p...
一分钟了解!樱花之盛辅助软件下... 一分钟了解!樱花之盛辅助软件下载!竟然真的有辅助app(有挂工具)-哔哩哔哩樱花之盛辅助软件下载破解...
6分钟了解!福建兄弟13水修改... 6分钟了解!福建兄弟13水修改器!一直是有辅助软件(有挂技术)-哔哩哔哩1)福建兄弟13水修改器免费...
第9分钟了解!顺欣茶坊智能辅助... 第9分钟了解!顺欣茶坊智能辅助器使用说明书!一贯一直总是有辅助软件(有挂解惑)-哔哩哔哩1、打开软件...
6分钟了解!四川游戏家园辅助软... 6分钟了解!四川游戏家园辅助软件!都是真的有辅助教程(有挂辅助)-哔哩哔哩;1、金币登录送、破产送、...
5分钟了解!约局吧脚本有用码!... 5分钟了解!约局吧脚本有用码!一直真的有辅助app(有挂方法)-哔哩哔哩运约局吧脚本有用码辅助工具,...
六分钟了解!八仙竞技馆辅助!一... 六分钟了解!八仙竞技馆辅助!一直一直总是有辅助技巧(有挂技术)-哔哩哔哩八仙竞技馆辅助辅助器是一种具...
第三分钟了解!途游四川辅助器小... 第三分钟了解!途游四川辅助器小程序!切实有辅助app(确实有挂)-哔哩哔哩该软件可以轻松地帮助玩家将...
2分钟了解!贰柒拾智能辅助柒!... 2分钟了解!贰柒拾智能辅助柒!切实真的是有辅助神器(有挂工具)-哔哩哔哩1、操作简单,无需贰柒拾智能...