angular - 如何逃避 Angular HttpParams?

标签 angular http

在 Angular 服务中,我使用 HttpParams 向服务发送字符串:

get(phone: string): Observable<PhoneSearchResponse> {
    let params = new HttpParams();
    params = params.append("phone", phone); // sending "+123456"
    return this._http.get<PhoneSearchResponse>(`${this._apiurl}/Get`, { params: params });
}

当使用 +123456 作为参数调用 get() 时,我将在接收服务中获得 123456。所以在某个地方 + 被转换为空格。

我是否需要对 HttpParams 进行转义以使它们在服务中保持不变?

如果重要的话,后端是一个 asp.net 核心项目。 Controller 中调用的代码:

[HttpGet("[action]")]
public async Task<JsonResult> Get(string phone) // receiving " 123456"
{
  return Json(await PhoneSearchLogic.GetAsync(phone));
}

[更新] Noémi Salaun 的解释非常好 - 但我想知道更改参数是否是“设计”的预期行为?或者是 ASP.NET Core Controller 的问题,它不应该对 + 号(和其他符号)进行转义?

最佳答案

源码中可以看到common/http/src/params.ts , HttpParams 使用默认编码器 HttpUrlEncodingCodec

HttpUrlEncodingCodec 使用 native encodeURIComponent 函数,但随后取消编码一些符号以满足 RFC 规范( native JS 实现不遵循)。

所以如果你想保持你的 + 符号编码,你可以在使用 HttpParams 之前手动编码它,或者你可以覆盖 HttpParameterCodec您自己的实现并通过 HttpParamOptions.encoder 属性传递它。

所有这些在现已弃用的 Http 服务中得到了更好的解释。使用它的 UrlSearchParamsQueryEncoder

源码中可以看到http/src/url_search_params.ts

By default, QueryEncoder encodes keys and values of parameters using encodeURIComponent, and then un-encodes certain characters that are allowed to be part of the query according to IETF RFC 3986: https://www.rfc-editor.org/rfc/rfc3986.

These are the characters that are not encoded: ! $ \' ( ) * + , ; A 9 - . _ ~ ? /

If the set of allowed query characters is not acceptable for a particular backend, QueryEncoder can be subclassed and provided as the 2nd argument to URLSearchParams.

关于angular - 如何逃避 Angular HttpParams?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49438737/

相关文章:

多个应用程序中的 Angular 共享 Assets

javascript - 类似于 Cron 作业的刷新 Angular 组件

Angular 无法分配给对象 'offsetTop' 的只读属性 '[object HTMLImageElement]'

java - 在一段时间后调用 API 时第一次获取连接重置异常

java - 在 Java 中使用 HTTP 请求发送 cookie

通过蓝牙的 HTTP

java - 将 Http Servlet 请求转换为 json 到我定义的对象

Angular2 - 将类添加到具有特定 id 的元素

javascript - ng2-smart-table如何更改自定义按钮在点击时的显示和隐藏

twitter-bootstrap - Bootstrap 无法从 maxcdn ERR_CONNECTION_RESET 加载