Angular路由带有查询参数和追加路由
创始人
2024-10-28 01:34:51
0

在Angular中,要在路由中传递查询参数,可以使用queryParams参数来传递查询参数。而要在追加路由时添加查询参数,可以使用queryParamsHandling参数。

以下是一个示例代码:

  1. 在路由模块中定义路由:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home.component';
import { ProductComponent } from './product.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'product', component: ProductComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  1. 在组件中导航到带有查询参数的路由:
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  template: `
    
    
  `,
})
export class HomeComponent {
  constructor(private router: Router) { }

  goToProduct() {
    this.router.navigate(['/product']);
  }

  goToProductWithQueryParams() {
    this.router.navigate(['/product'], { queryParams: { id: 1, name: 'Product A' } });
  }
}
  1. 在接收查询参数的组件中,可以通过ActivatedRoute服务来获取查询参数:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product',
  template: `
    

Product Details

ID: {{ id }}

Name: {{ name }}

`, }) export class ProductComponent implements OnInit { id: string; name: string; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.queryParams.subscribe(params => { this.id = params['id']; this.name = params['name']; }); } }

在这个示例中,点击"Go to Product"按钮会导航到Product组件,而点击"Go to Product with Query Params"按钮会导航到Product组件并传递查询参数。在Product组件中,通过ActivatedRoute服务获取查询参数,并将其显示在组件模板中。

希望这个示例能帮助到你!

相关内容

热门资讯

大家学习交流!wepoker透... 大家学习交流!wepoker透视苹果系统,德普之星辅助工具如何设置,好像是有挂(有挂详细)运辅助工具...
安装程序教程!wepokerp... 安装程序教程!wepokerplus万能挂,wpk透视插件,切实是真的有挂(有挂分析)1、玩家可以在...
推荐十款!wepoker如何设... 推荐十款!wepoker如何设置透视,wepoker智能辅助插件,竟然是真的有挂(有挂助手)1、we...
推荐十款!wepoker手机版... 推荐十款!wepoker手机版透视脚本,wepoker游戏下载,好像存在有挂(有挂秘笈)1、操作简单...
一分钟了解!德州透视插件,we... 一分钟了解!德州透视插件,wepoker私人局辅助器怎么用,切实是真的有挂(确实有挂)暗藏猫腻,小编...
推荐一款!德普之星透视辅助,w... 推荐一款!德普之星透视辅助,wepoker软件靠谱么,果然有挂(有挂方法)1、这是跨平台的轻量版有透...
发现一款!wepoker有没有... 发现一款!wepoker有没有透视方法,扑克之星辅助,其实是有挂(有挂教程)1、任何透视是真的假的的...
重大推荐!德州透视插件,pok... 重大推荐!德州透视插件,pokemmo手机版脚本,一贯真的有挂(新版有挂)1、用户打开应用后不用登录...
玩家交流!wepoker轻量版... 玩家交流!wepoker轻量版辅助,wepoker软件辅助程序,果然真的有挂(详细教程)1. 选牌创...
玩家攻略推荐!pokemmo手... 玩家攻略推荐!pokemmo手机辅助软件,hhpoker底牌透视脚本,真是真的是有挂(有挂教程)一、...