2017-06-01 78 views
0

我正在用TypeScript制作一个简单的Angular(版本4)应用程序。从Angular URL中提取多个参数

我有一个看起来像这样的URL: www.example.com/api/1/countries/Italy/

我想从这个URL 1Italy,并将其分配给变量。

我试着用ActivatedRoute这样的:

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

idcountry是我的私有变量我想从URL中的赋值。但我不知道如何进行......

我还需要做什么?

+1

请看溶液[此帖](https://stackoverflow.com/a/39146396/6036154) – embarq

+1

'1'和'Italy'不查询参数,它们是路由参数。 –

回答

1

在您的URL示例中,您不使用查询参数。因此,代码从ActivatedRoute获取值看起来是这样的:

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

此代码假定你已经使用参数名为id和国家,例如配置你的路由

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

+0

谢谢!但是如果我只有一个Component。这样做是否有意义:'{path:'/ api /:id/countries /:country /',component:IndexPageComponent}'? – lapadets

+1

是的,它会工作。你可能不需要主要的正斜杠。 –

0

您可以使用DOCUMENT访问URL并解析它。

component.ts

import { DOCUMENT } from '@angular/platform-browser'; 

    constructor(@Inject(DOCUMENT) document: any) { 
    console.log(document.location.href); 
    }