0

I want to invoke a REST API in Angular4 containing URL parameters. The template looks like that:

http://localhost:61448/api/Product/language/{languauge}/name/{name}

This is a working example:

http://localhost:61448/api/Product/language/en-us/name/apple

I know I can just concat the URL myself:

this.http.get<Array<ProductResponse>>('http://localhost:61448/api/Product/language/' + 'en-us' + '/name/' + 'apple',)
      .subscribe(data => {
      // do something with data
    });

But I was hoping to find a better solution using something like HttpParams:

const params = new HttpParams()
.set('language', 'en-us')
.set('name', 'apple');

this.http.get<Array<ProductResponse>>('http://localhost:61448/api/Product', {params : params}).subscribe(data => {
  // do something with data
});

But this will generate the following request (containing query parameter):

http://localhost:61448/api/Product?language=en-us&name=apple

Is there any way to generate the right URL without concat it myself?

4
  • Take a look at this answer... https://stackoverflow.com/a/41533506/5874913 Commented Oct 20, 2017 at 7:17
  • 1
    @seven Your suggested answers doesn't help me, they are using query parameters! Please remove the duplicate flag. Commented Oct 20, 2017 at 7:21
  • 1
    The answer is no. Just use template strings to make it slightly more readable. Commented Oct 20, 2017 at 7:32
  • @JBNizet Yes, template string will make it more readable, thanks Commented Oct 20, 2017 at 7:33

1 Answer 1

1

instead of:

this.http.get<Array<ProductResponse>>('http://localhost:61448/api/Product/language/' + 'en-us' + '/name/' + 'apple',)
      .subscribe(data => {
      // do something with data
    });

do:

this.http.get<Array<ProductResponse>>(`http://localhost:61448/api/Product/language/${languauge}/name/${name}`,)
      .subscribe(data => {
      // do something with data
    });

where language and name are your params.

notice special quotes character for url and your params must be inside ${}

ref link: https://basarat.gitbooks.io/typescript/docs/template-strings.html

Sign up to request clarification or add additional context in comments.

2 Comments

Thats not exactly what I was looking for but way better then my aproach and enough for me. Thanks!
well, from my understanding of your question, what you're looking for is pretty much impossible as typescript/angular cannot know where in the url to puth which variable. you have to have anchors for it. and that's what this methods is for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.