gpt4 book ai didi

angular - URLSearchParams 不是构造函数

转载 作者:行者123 更新时间:2023-12-03 08:57:03 25 4
gpt4 key购买 nike

我有一个 Angular 服务,我尝试发送 HTTP Post 请求并设置Content-Type header 到 application/x-www-form-urlencoded

这是代码:

import { HttpClient, HttpHeaders } from '@angular/common/http';
export class UserService {
constructor(private http:HttpClient, private bodyParser:BodyParserService{}

public login(username:String, password:String){
let body = this.bodyParser.parseBody({username: username, password: password})
const options = {
headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})

};
this.http.post(`${environment.apiUrl}/login`, body, options)
.subscribe((response:any) => {
console.log("Response", response);
})
}

}

我正在使用 Angular7。我使用 Chrome 浏览器,但在 FireFox 上问题仍然存在

我收到以下错误:

ERROR TypeError: url__WEBPACK_IMPORTED_MODULE_2__.URLSearchParams is not a constructor
at BodyParserService.push../src/app/services/body-parser.service.ts.BodyParserService.parseBody (body-parser.service.ts:12)
at UserService.push../src/app/services/user-service.service.ts.UserService.login (user-service.service.ts:21)
at LoginModalComponent.push../src/app/nav-bar/nav-bar.component.ts.LoginModalComponent.login (nav-bar.component.ts:50)
at Object.eval [as handleEvent] (LoginModalComponent.html:19)
at handleEvent (core.js:19545)
at callWithDebugContext (core.js:20639)
at Object.debugHandleEvent [as handleEvent] (core.js:20342)
at dispatchEvent (core.js:16994)
at core.js:17441
at HTMLButtonElement.<anonymous> (platform-browser.js:993)

我已经确定我已经导入了 HttpClientModule

bodyParser 服务:

import { Injectable } from '@angular/core';
import { URLSearchParams } from 'url';

@Injectable({
providedIn: 'root'
})
export class BodyParserService {

constructor() { }

public parseBody(bodyObject: Object): string {
const body = new URLSearchParams();
Object.keys(bodyObject).forEach(key => {
body.set(key.toString(), bodyObject[key]);
});
return body.toString();
}
}

好吧,我发现了我的错误:URLSearchParams 似乎已被弃用。我现在已经使用 HttpParams 来代替:

const body = new HttpParams();

最佳答案

URLSearchParams 已弃用,您必须使用 HttpParams。例如

let params = new HttpParams()
.set('grant_type', 'password')
.set('username', username)
.set('password', password);

params.toString();

关于angular - URLSearchParams 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com