如何停止将+符号转换为Angular中的空间

时间:2019-03-09 04:38:55

标签: angular angular5

searchItem包含一些值,例如abc + def。当我在后端检查时它会像(abc def)。如何固定。+(加号转换为空格)

search(searchItem: string): Promise<any> {
    let params = new HttpParams();
    params = params.append('searchItem', searchItem);
    return new Promise((resolve, reject) => {
        // use For Testing
        this.httpClient.get(this.urlService.getApiUrl() + 'test/item',
                {
                    params: params
                })
        .subscribe(data => {
            resolve(data);
        }, error => {
            console.log('Error: ' + JSON.stringify(error));
            reject(error);
        });
    });
}

2 个答案:

答案 0 :(得分:0)

您只需要在设置参数之前调用encodeURIComponent()方法。

...
params = params.append('searchItem', encodeURIComponent(searchItem));
...

答案 1 :(得分:0)

使用HttpParams的自定义编码器来解决此问题。

import { HttpParameterCodec } from '@angular/common/http';

export class CustomEncoder implements HttpParameterCodec {
  encodeKey(key: string): string {
    return encodeURIComponent(key);
  }

  encodeValue(value: string): string {
    return encodeURIComponent(value);
  }

  decodeKey(key: string): string {
    return decodeURIComponent(key);
  }

  decodeValue(value: string): string {
    return decodeURIComponent(value);
  }
}

,然后在您的search()函数中,

let params = new HttpParams({encoder: new CustomEncoder()});