在Angular 6服务中设置api url的参数

问题描述 投票:1回答:2

我有一个需要传递一些数据的get请求,我该如何在我的服务中执行此操作:

private campaignUrl = environment.apiUrl + '/campaign/';

    constructor(private http: HttpRequestService) { }

    getCampaign(uuid) {
        return this.http.post(this.campaignUrl);
    }

我需要在campaignUrl之后传递id,这是我心血来潮的api url:

/ API /运动/ {UUID} /

angular
2个回答
2
投票

另一个答案是足够的,但我会提供这个,因为你几乎在你的例子,使用ES6 template literals(反蜱):

private campaignUrl = environment.apiUrl + '/campaign/';

constructor(private http: HttpRequestService) { }

getCampaign(uuid) {
    return this.http.get(`${this.campaignUrl}/${encodeURI(uuid)}`);
}

或带箭头

getCampaign = (uuid) => this.http.get(`${this.campaignUrl}/${encodeURI(uuid)}`);

请注意,您可能想要调用encodeURI()(因为Angular不会为您执行此操作)。如果你可以保证传递给getCampaign的字符串总是一个uuid格式(nnnn-nnnn-...),你可以跳过这个。

另外,你在你的问题中说“获取请求”但是调用.post,所以我认为你的文本是正确的,代码不是。


3
投票

是获得还是帖子?

无论如何你可以这样做:

return this.http.post(this.campaignUrl + uuid);
© www.soinside.com 2019 - 2024. All rights reserved.