Angular路由参数默认值不起作用的问题
创始人
2024-10-28 01:00:34
0
  1. 使用 || 运算符:

在定义路由参数时,可以使用 || 运算符来给特定参数设置默认值。例如:

const routes: Routes = [ { path: 'user/:id', component: UserProfileComponent }, { path: 'user/:id/:name', component: UserProfileComponent }, { path: '**', redirectTo: 'home' } ];

在上述代码中,用户的 ID 和名称都是路由参数,默认情况下,如果未指定名称,名称将为空字符串。通过使用 || 运算符,我们可以将名称设置为“未知”,如下所示:

const routes: Routes = [ { path: 'user/:id', component: UserProfileComponent }, { path: 'user/:id/:name', component: UserProfileComponent, data: { name: 'unknown' || params.name } }, { path: '**', redirectTo: 'home' } ];

  1. 使用 ActivatedRoute:

我们还可以使用 ActivatedRoute 来获取当前路由参数并设置默认值。在组件中,我们可以注入 ActivatedRoute 并使用 Snapshot 获取当前参数。例如:

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

@Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.css'] }) export class UserProfileComponent implements OnInit {

id: string; name: string;

constructor(private route: ActivatedRoute) { }

ngOnInit() { this.id = this.route.snapshot.paramMap.get('id'); this.name = this.route.snapshot.paramMap.get('name') || 'unknown'; }

}

在上述代码中,ngOnInit() 方法获取当前路由参数,并将名称设置为“未知”,如果没有指定名称。这样就可以确保默认值始终起作用。

相关内容

热门资讯

玩家必看科普!wepokerh... 玩家必看科普!wepokerh5破解,wepoker透视破解版,解密教程(有挂技巧);玩家必备必赢加...
盘点一款!德州局透视脚本免费版... 盘点一款!德州局透视脚本免费版下载手机版,wepoker私人局怎么玩,可靠教程(有挂神器);《WPK...
一分钟了解!pokemmo手机... 一分钟了解!pokemmo手机版修改器,wejoker辅助软件视频,黑科技教程(有挂透视);玩家必备...
实测分享!wpk透视辅助下载,... 1、实测分享!wpk透视辅助下载,wepoker辅助器如何使用,攻略教程(有挂攻略);详细教程。2、...
玩家必看科普!epoker透视... 玩家必看科普!epoker透视,wepoker黑侠辅助器,透明挂教程(有挂软件)1、很好的工具软件,...
总算清楚!aapoker安装包... 总算清楚!aapoker安装包怎么使用,智星菠萝可以辅助吗,总结教程(有挂教程)是一款可以让一直输的...
避坑细节!pokemmo辅助脚... 避坑细节!pokemmo辅助脚本,wepokerplus开挂,教你攻略(有挂技巧);支持多人共享记分...
玩家科普!wejoker辅助器... 玩家科普!wejoker辅助器怎么卖,hhpoker是正品吗,必备教程(有挂方法);原来确实真的有挂...
最新技巧!hhpoker德州透... 最新技巧!hhpoker德州透视挂,wejoker辅助机器人,黑科技教程(有挂技巧);人气非常高,a...
盘点几款!wepoker透视脚... 盘点几款!wepoker透视脚本是什么,wepoker有插件吗,细节揭秘(有挂透视);建议优先通过w...