How do I add query parameters to my url in TypeScript?

时间:2019-04-08 13:36:25

标签: typescript

After I click on a button, I want to redirect to a different page. So I have the following function:

//this redirects me correctly
click() {
    window.location.href = 'download/' + this.some.string.toLowerCase();
    console.log(this.client.displayName);
  }

However I would like my url to look something like this:

toggleDownload() {
    const someValue = this.client.getValue();
    window.location.href = 'download/' + this.client.displayName.toLowerCase()+'key='+value;
    console.log(this.client.displayName);
  }

If the query parameters are presented, I do something based on this, if not, I don't. Is this the correct way to add query parameters? Do I just append them as string?

1 个答案:

答案 0 :(得分:1)

Use template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

This will remove the need to manually concatenate the substrings into one, as shown below:

toggleDownload(): void {
    const someValue = this.client.getValue();
    const urlWithParams = `download/${this.client.displayName.toLowerCase()}+key=${value}`;
    window.location.href = urlWithParams;
  }