使用Angular从URL中提取多个参数(Extract more than one parameter from URL with Angular)

编程入门 行业动态 更新时间:2024-10-21 14:31:59
使用Angular从URL中提取多个参数(Extract more than one parameter from URL with Angular)

我正在使用TypeScript创建一个简单的Angular(版本4)应用程序。

我有一个如下所示的网址: www.example.com/api/1/countries/Italy/

我想从这个URL获得1和Italy并将它们分配给变量。

我尝试使用ActivatedRoute :

ngOnInit() { this.router .queryParams .subscribe(params => { this.id = +params['']; this.country = +params['']; }); }

其中id和country是我的私有变量,我想用URL中的值进行分配。 但我不知道如何继续......

我还需要做什么?

I am making a simple Angular (version 4) application with TypeScript.

I have an URL that looks like this: www.example.com/api/1/countries/Italy/

And I want to get 1 and Italy from this URL and assign them to variables.

I tried with ActivatedRoute like this:

ngOnInit() { this.router .queryParams .subscribe(params => { this.id = +params['']; this.country = +params['']; }); }

Where idand country are my private variables I want to assign with the values from the URL. But I don't know how exactly to proceed...

What else do I need to do?

最满意答案

在您的URL示例中,您不使用查询参数。 因此,从ActivatedRoute获取值的代码可能如下所示:

this.id = this.route.snapshot.paramMap.get('id'); this.country = this.route.snapshot.paramMap.get('country');

此代码假定您已使用名为id和country的params配置路由,例如

{path: 'api/:id', component: CompA} ... {path: 'countries/:country', component: CompB}

In your URL example you don't use query parameters. So the code to get values from the ActivatedRoute could look like this:

this.id = this.route.snapshot.paramMap.get('id'); this.country = this.route.snapshot.paramMap.get('country');

This code assumes that you have configured your routes with params named id and country, e.g.

{path: 'api/:id', component: CompA} ... {path: 'countries/:country', component: CompB}

更多推荐

本文发布于:2023-08-07 19:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   参数   URL   Angular   Extract

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!