URLSearchParams不是构造函数

时间:2019-02-09 21:05:30

标签: angular typescript http-headers angular-httpclient

我有一个Angular服务,我尝试在其中发送HTTP Post请求并设置 Content-Type的{​​{1}}标题

这是代码:

application/x-www-form-urlencoded

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

我收到以下错误:

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

}

我已确保已导入HttpClientModule

bodyParser服务:

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)

好的,我发现了我的错误: URLSearchParams似乎已被弃用。我现在改用了HttpParams:

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

2 个答案:

答案 0 :(得分:0)

我已经为答案添加了正确的解决方案。 URLSearchParams似乎已被弃用。所以我切换到HttpParams到位,看来工作无懈可击

答案 1 :(得分:0)

不建议使用URLSearchParams,必须使用HttpParams。例如

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

params.toString();