簡體   English   中英

使用Angular從URL中提取多個參數

[英]Extract more than one parameter from URL with Angular

我使用TypeScript制作了一個簡單的Angular(版本4)應用程序。

我有一個看起來像這樣的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中的值進行分配。 但我不知道該如何進行...

我還需要做什么?

在您的URL示例中,您不使用查詢參數。 因此,從ActivatedRoute獲取值的代碼如下所示:

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

此代碼假定您已使用名為id和country的參數配置了路由,例如

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

您可以使用DOCUMENT訪問URL並進行解析。

component.ts

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM