此服务应该对我的 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/