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服务获取查询参数,并将其显示在组件模板中。

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

相关内容

热门资讯

有玩家发现!newpoker脚... 有玩家发现!newpoker脚本(透视)原来真的有挂(有挂解惑开挂辅助辅助器)-哔哩哔哩1、首先打开...
记者获悉!wepoker怎么看... 您好,wepoker怎么看底牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
昨日!wepoker透视脚本(... 昨日!wepoker透视脚本(透视)其实确实有挂(真实有挂开挂辅助工具)-哔哩哔哩1、在wepoke...
为切实保障!wepoker透视... 为切实保障!wepoker透视有吗,pokerrrr2辅助,方针教程(有挂技术)-哔哩哔哩1、起透看...
为了进一步!hhpoker怎么... 为了进一步!hhpoker怎么破解(透视)原来是有挂(有挂方针开挂辅助下载)-哔哩哔哩1、完成hhp...
近日!智星菠萝透视,智星菠萝透... 近日!智星菠萝透视,智星菠萝透视,模板教程(有挂透明挂)-哔哩哔哩1、全新机制【智星菠萝透视软件透明...
截至目前!wepoker免费脚... 截至目前!wepoker免费脚本咨询(透视)原来有挂(有挂秘笈开挂辅助平台)-哔哩哔哩1、任何wep...
有了最新消息!xpoker辅助... 有了最新消息!xpoker辅助神器,wepoker怎么发冤家牌,策略教程(有挂教程)-哔哩哔哩1、在...
据通报!wpk模拟器(透视)其... 据通报!wpk模拟器(透视)其实是有挂(有挂分享开挂辅助插件)-哔哩哔哩wpk模拟器辅助器中分为三种...
长期以来!拱趴大菠萝万能挂图解... 长期以来!拱趴大菠萝万能挂图解,steampokermaster辅助,方针教程(有挂规律)-哔哩哔哩...