简体   繁体   English

如何使用get http请求发送参数(id)?

[英]How to send a parameter (id) with get http request?

I started typing and http.get accepts only url so i don't have any idea how to send and id of a person to get that person from my api which gets it from Sql database . 我开始输入,而http.get只接受url,所以我不知道如何发送一个人的ID并从我的api(从Sql数据库中获取它)中获取该人。

public getByID(n :number) : Promise<any>{

    return this.http.get(this.url).toPromise();
  }

maybe appending it to an url ? 也许将其附加到网址?

您可以选择使用模板字符串将参数添加到URL

return this.http.get(`${this.url}?id=${n}`).toPromise();

If you want to pass variables to the API using GET that would be possible using query string. 如果您想使用GET将变量传递给API,则可以使用查询字符串。 Remember to escape (urlencode) them properly! 记住要正确地逃避(urlencode)! It is also possible to use POST, if you dont want your variables to be visible. 如果您不希望变量可见,也可以使用POST。

Manually formatting the query string is fine for simple situations. 对于简单的情况,手动设置查询字符串的格式很好。 But it can become tedious when there are many parameters. 但是,如果有许多参数,它可能会变得乏味。

You could write a simple utility function that handles building the query formatting for you. 您可以编写一个简单的实用程序函数来为您构建查询格式。

function formatParams( params ){
return "?" + Object
    .keys(params)
    .map(function(key){
        return key+"="+encodeURIComponent(params[key])
    })
    .join("&")

} }

And you would use it this way to build a request. 您将以这种方式使用它来构建请求。

var endpoint = "https://api.example.com/endpoint"
var params = {
a: 1,
b: 2,
c: 3
}


return this.http.get(this.url+ formatParams(params)).toPromise();

Here is an example of what you would need to do 这是您需要做的一个例子

public getByID(n :number) : Promise<any>{  
    return this.http.get(this.url + '?id=' + number).toPromise();
}

If you want to pass id you can just make post request. 如果你想传递id ,你可以只是做post的要求。 It would like return this.http.post(this.url, {id: n}).toPromise() , second argument is just body of request, it can be an array of object, or just object. 它想return this.http.post(this.url, {id: n}).toPromise() ,第二个参数只是请求体,可以是对象数组,也可以是对象。 Then on the server side you just have to parse it to JSON format. 然后在服务器端,您只需将其解析为JSON格式。 You can also use get method, but then you have to send it as search url param. 您也可以使用get方法,但随后必须将其作为搜索URL参数发送。 Take a look at this here 这里看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM