在Angular中REST请求添加了破坏请求的字符,可以使用encodeURIComponent()
函数对请求参数进行编码,以确保特殊字符被正确处理。
以下是一个示例,演示了如何在Angular中进行REST请求并使用encodeURIComponent()
函数对参数进行编码:
import { HttpClient, HttpParams } from '@angular/common/http';
// ...
@Injectable()
export class YourService {
constructor(private http: HttpClient) { }
yourRestRequest(yourParam: string) {
// 对参数进行编码
const encodedParam = encodeURIComponent(yourParam);
// 创建HTTP参数对象并将编码后的参数添加到其中
let params = new HttpParams();
params = params.set('yourParam', encodedParam);
// 发起REST请求
return this.http.get('your-api-url', { params: params });
}
}
在上面的示例中,首先使用encodeURIComponent()
对yourParam
进行编码。然后,使用HttpParams
创建一个HTTP参数对象,并使用set()
方法将编码后的参数添加到其中。最后,将参数对象作为选项传递给http.get()
方法来发起REST请求。
这样,特殊字符将被正确编码,以避免破坏请求。