2017-07-08 94 views
1

這種服務應該執行HTTP POST請求我的PHP後端API,但NG2不會編譯項目,它引發以下錯誤:Angular2 HTTP POST頭參數類型錯誤

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應用程序。

+2

錯誤文本顯示的標頭值是'Headers'大寫字母H,但是您的代碼示例顯示了帶有小h的'Header'。請確保您準確地重現代碼和錯誤。 – BeetleJuice

回答

2

你必須使用:

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

更新登錄方法:

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

經過測試,但仍然是相同的錯誤。 – Haarvey

+2

@Haarvey檢查你的導入,你應該導入的Headers類型是'@ angular/http''; import {Headers}。 –

+0

如果這個答案對您有幫助,請接受並告訴我您是否需要任何幫助。 –

0

我有同樣的問題,將報頭添加進口的伎倆(感謝Subtain Ishfaq)

從「@ angular/http」導入{Http,Headers};