如何通过Angular路由实现跳转并使用GET方式传递参数?

2026-04-20 00:081阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计415个文字,预计阅读时间需要2分钟。

如何通过Angular路由实现跳转并使用GET方式传递参数?

场景+通过上面了解了解释了路由配置后,需要实现路由跳转并传递值,例如在新闻页面点击某条新闻跳转到新闻详情页,并将当前新闻的id传递过去。+ 注意:+ 公众号+ 需要编写程序代码+ 获取编程相关内容

场景

通过上面了解了路由配置后,要实现路由跳转并传值,比如在新闻页面点击某条新闻跳转到新闻详情并将当前新闻的id传递过去。

注:

​​ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。

实现

首先在新闻news组件中声明一个空数组并赋一些值

public list:any[] = [];

在初始化方法中赋值

ngOnInit(): void { for(var i=0;i<10;i++) { this.list.push("这是第"+i+"条数据"); } }

然后在app.routing.module.ts中引入新闻详情的组件并设置新闻详情的路由

import {NewsdetailComponent} from './components/newsdetail/newsdetail.component';const routes: Routes = [ {path:'newsdetail',component:NewsdetailComponent}];

然后在新闻页面中添加跳转链接

<ul> <li *ngFor = "let item of list;let key=index;"> <a [routerLink]="['/newsdetail']" [queryParams]="{aid:key}">{{key}}--{{item}}</a> </li></ul>

通过queryParams将当前新闻的索引进行传递参数。

那么怎样在新闻详情页接受这个参数。

首先在新闻详情页引入ActivatedRoute模块

import {ActivatedRoute} from '@angular/router';

然后去声明

constructor(public route:ActivatedRoute) { }

最后获取传递的参数

如何通过Angular路由实现跳转并使用GET方式传递参数?

ngOnInit(): void { this.route.queryParams.subscribe((data)=>{ console.log(data); }); }

就可以获取到传递的参数

这样就能通过get传值的方式获取到传递的参数,可以在url中看到传递的参数

本文共计415个文字,预计阅读时间需要2分钟。

如何通过Angular路由实现跳转并使用GET方式传递参数?

场景+通过上面了解了解释了路由配置后,需要实现路由跳转并传递值,例如在新闻页面点击某条新闻跳转到新闻详情页,并将当前新闻的id传递过去。+ 注意:+ 公众号+ 需要编写程序代码+ 获取编程相关内容

场景

通过上面了解了路由配置后,要实现路由跳转并传值,比如在新闻页面点击某条新闻跳转到新闻详情并将当前新闻的id传递过去。

注:

​​ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。

实现

首先在新闻news组件中声明一个空数组并赋一些值

public list:any[] = [];

在初始化方法中赋值

ngOnInit(): void { for(var i=0;i<10;i++) { this.list.push("这是第"+i+"条数据"); } }

然后在app.routing.module.ts中引入新闻详情的组件并设置新闻详情的路由

import {NewsdetailComponent} from './components/newsdetail/newsdetail.component';const routes: Routes = [ {path:'newsdetail',component:NewsdetailComponent}];

然后在新闻页面中添加跳转链接

<ul> <li *ngFor = "let item of list;let key=index;"> <a [routerLink]="['/newsdetail']" [queryParams]="{aid:key}">{{key}}--{{item}}</a> </li></ul>

通过queryParams将当前新闻的索引进行传递参数。

那么怎样在新闻详情页接受这个参数。

首先在新闻详情页引入ActivatedRoute模块

import {ActivatedRoute} from '@angular/router';

然后去声明

constructor(public route:ActivatedRoute) { }

最后获取传递的参数

如何通过Angular路由实现跳转并使用GET方式传递参数?

ngOnInit(): void { this.route.queryParams.subscribe((data)=>{ console.log(data); }); }

就可以获取到传递的参数

这样就能通过get传值的方式获取到传递的参数,可以在url中看到传递的参数