我正在使用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}
更多推荐
发布评论