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?

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172

1 Answers1

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

dee zg
  • 13,793
  • 10
  • 42
  • 82
  • Thats not exactly what I was looking for but way better then my aproach and enough for me. Thanks! – Martin Brandl Oct 20 '17 at 07:33
  • 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. – dee zg Oct 20 '17 at 07:34