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

相关内容

热门资讯

大家学习交流!wepoker手... 大家学习交流!wepoker手机版透视脚本,wepoker游戏下载,切实真的有挂(的确有挂)1、在w...
一分钟了解!we-poker辅... 一分钟了解!we-poker辅助器,wepoker透视脚本是什么,总是是有挂(有挂方略)1、透视辅助...
玩家必看教程!wpk透视辅助方... 玩家必看教程!wpk透视辅助方法,wepoker有辅助插件吗,好像是真的有挂(有挂存在)1、金币登录...
重大通报!hhpoker外挂靠... 重大通报!hhpoker外挂靠谱吗,wepoker透视方法,其实是有挂(有挂分析)1、模拟器是什么优...
我来分享!hhpoker作弊码... 我来分享!hhpoker作弊码,德普之星私人局辅助器,一直有挂(有挂解惑)1、起透看视 德普之星私人...
玩家必看教程!wepoker透... 玩家必看教程!wepoker透视脚本免费下载,aapoker怎么拿好牌,切实有挂(有挂功能)所有人都...
今日公布!hhpoker有没有... 今日公布!hhpoker有没有外挂,wepoker私人局俱乐部怎么进,总是有挂(有挂细节)1、点击下...
最新技巧!约局吧德州可以透视吗... 最新技巧!约局吧德州可以透视吗,wepoker究竟有没有透视,都是真的是有挂(有挂教学)1、游戏颠覆...
科技通报!wpk透视辅助下载,... 科技通报!wpk透视辅助下载,wpk是真的还是假的,都是存在有挂(有挂功能)1、进入游戏-大厅左侧-...
盘点一款!hhpoker外挂靠... 盘点一款!hhpoker外挂靠谱吗,wepoker到底有没有透视,一直是有挂(有挂方略)1、实时透视...