Angular2 Http POST header 参数类型错误

标签 angular http header

此服务应该对我的 PHP 后端 api 执行 HTTP post 请求,但 ng2 不会编译该项目,它会抛出以下错误:

ERROR in login-service.ts (25,9): Argument of type '{ headers: Headers; }' is not assignable to parameter of type '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'.

我的代码片段如下所示:

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

此代码在不同的 ng2 应用程序中完美运行。

最佳答案

我遇到了同样的问题,在导入中添加 header 就解决了问题(感谢 Subtain Ishfaq)

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

关于Angular2 Http POST header 参数类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44986638/

相关文章:

javascript - Angular:未收到事件发射器

java - 打开远程文件并写入

http - 当表单没有发布到它所在的页面时,返回错误状态的最佳方法是什么?

java - 如何有效地重用 HttpClient 连接?

pandas - 如何在一系列 Pandas 中显示标题?

javascript - 无法从 angular4 中的嵌套函数访问它

javascript - Angular - 如何从 Firebase DB 中删除数据

javascript - return 语句中的 OR 条件

Python - 定义常量列表或字典的最佳/最简洁方式

html - 页面顶部的页眉间隙