2017-10-20 34 views
0

我想在Angular4中调用包含URL参数的REST API。模板看起来像这样:Angular4 http获得URL参数

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

这是一个工作示例:

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

我知道我可以只CONCAT的URL自己:

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

但我希望能找到一个使用类似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 
}); 

但是,这将产生以下的请求(包含查询参数):

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

有什么办法来产生不CONCAT它自己正确的网址是什么?

+0

看看这个答案... [https://stackoverflow.com/a/41533506 /5874913](https://stackoverflow.com/a/41533506/5874913) – seven

+1

@seven您的建议答案不能帮助我,他们正在使用查询参数!请删除重复的标志。 –

+1

答案是否定的。只需使用模板字符串,使其更具可读性。 –

回答

1

代替:

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

做:

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

其中languagename是您的PARAMS。

的URL

通知特别报价的性格和你的PARAMS必须是内${}

参考链接: https://basarat.gitbooks.io/typescript/docs/template-strings.html

+0

这不是我正在寻找的东西,但方式更好,然后我的aproach和足够的我。谢谢! –

+0

好吧,根据我对你的问题的理解,你正在寻找的东西几乎是不可能的,因为typescript/angular无法知道在哪个url中puth哪个变量。你必须有锚。这就是这种方法的用途。 –