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() 方法获取当前路由参数,并将名称设置为“未知”,如果没有指定名称。这样就可以确保默认值始终起作用。

相关内容

热门资讯

黑科技好友房!wepokeai... 黑科技好友房!wepokeai辅助(透明挂)从来存在有挂(有挂识别)-哔哩哔哩1、不需要AI权限,帮...
黑科技智能ai!wopoker... 黑科技智能ai!wopoker辅助(智能ai)先前是真的有挂(有挂胜率)-哔哩哔哩;人气非常高,ai...
黑科技脚本!wpk输赢机制(黑... 黑科技脚本!wpk输赢机制(黑科技ai)起初是有挂(有挂靠谱)-哔哩哔哩;科技安装教程;136704...
黑科技透明挂!wepkoe黑科... 您好,wepkoe黑科技设备这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多...
黑科技存在!云扑克辅助器(ai... 黑科技存在!云扑克辅助器(ai辅助)总是真的是有挂(有挂猫腻)-哔哩哔哩,支持语音通讯、好友开房及战...
黑科技有挂!hm3德州辅助怎么... 黑科技有挂!hm3德州辅助怎么购买(黑科技ai)原生存在有挂(有挂玄学)-哔哩哔哩是一款可以让一直输...
黑科技了解!手机云扑克辅助(黑... 黑科技了解!手机云扑克辅助(黑科技)都是真的是有挂(有挂长期)-哔哩哔哩;小薇(透视辅助)致您一封信...
黑科技透明挂!wpk外挂是真的... 黑科技透明挂!wpk外挂是真的还是假的(辅助挂)先前真的有挂(有挂机器人)-哔哩哔哩是一款可以让一直...
黑科技透明挂!wpk有机器人吗... 黑科技透明挂!wpk有机器人吗(ai辅助)往昔是有挂(有挂智能)-哔哩哔哩;小薇(透视辅助)致您一封...
黑科技神器!好运大菠萝有没有挂... 黑科技神器!好运大菠萝有没有挂的(黑科技)确实有挂(有挂模拟器)-哔哩哔哩;科技安装教程;13670...