首页 > 解决方案 > 如何停止在Angular中将+符号转换为空格

问题描述

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);
        });
    });
}

标签: angularangular5

解决方案


使用自定义编码器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()});

推荐阅读