简体   繁体   English

Angular2 Http POST标头参数类型错误

[英]Angular2 Http POST header argument type error

This service should perform a HTTP post request to my PHP backend api, but ng2 won't compile the project, it throws the following error: 该服务应向我的PHP后端api执行HTTP发布请求,但是ng2不会编译该项目,它会引发以下错误:

ERROR in login-service.ts (25,9): Argument of type '{ headers: Headers; login-service.ts中的错误(25,9):类型'{标题的参数:标题; }' is not assignable to parameter of type 'RequestOptionsArgs'. }”不可分配给“ RequestOptionsArgs”类型的参数。 Types of property 'headers' are incompatible. 属性“标题”的类型不兼容。 Type 'Headers' is not assignable to type 'Headers'. 不能将类型“标题”分配给类型“标题”。 Two different types with this name exist, but they are unrelated. 存在两种使用此名称的不同类型,但是它们是无关的。 Property 'keys' is missing in type 'Headers'. 类型“标头”中缺少属性“键”。

My snippet looks like: 我的代码段看起来像:

import { HttpModule }     from '@angular/http';
import { Injectable }     from '@angular/core';
import { Http }           from '@angular/http';
import { Response }       from '@angular/http';
import { Headers }        from '@angular/http';

@Injectable()
export class LoginService {
  constructor(private http: Http) {

  }
  login(username, password){
    var body = 'foo=bar&foo1=bar1';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http
    .post('http://127.0.0.1/server.php', body, { headers: headers })
    .subscribe((data:Response) => {
       let res = data.text();
       console.log('Result: ',res);
     }, error => {
       console.log('Error: ', JSON.stringify(error.json()));
     });
  }
}

This code works perfectly in a different ng2 app. 此代码可在其他ng2应用中完美运行。

I had the same issue, adding Headers to the imports did the trick (thanks Subtain Ishfaq) 我遇到了同样的问题,在导入文件中添加Headers可以解决问题(感谢Subtain Ishfaq)

import {Http, Headers} from "@angular/http"; 从“ @ angular / http”导入{Http,Headers};

You have to use: 您必须使用:

let options = new RequestOptions({ headers: headers });

Updated Login Method: 更新的登录方法:

 login(username, password){
    var body = 'foo=bar&foo1=bar1';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({ headers: headers });
    this.http
    .post('http://127.0.0.1/server.php', body, options)
    .subscribe((data:Response) => {
       let res = data.text();
       console.log('Result: ',res);
     }, error => {
       console.log('Error: ', JSON.stringify(error.json()));
     });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM