2017-07-08 26 views
1

このサービスは、私のPHPのバックエンドAPIにHTTP POSTリクエストを行う必要がありますが、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

エラーテキストには、ヘッダーの値が大文字のHの「ヘッダー」として表示されますが、コードサンプルには小文字の「ヘッダー」が表示されます。コードとエラーを正確に再現してください。 – 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があなたのインポートをチェックします。あなたがインポートするヘッダタイプは、 '@ angular/http'からimport {ヘッダ}です。 –

+0

この回答が役に立った場合は、それ以上の助けが必要な場合は、同意してお知らせください。 –

0

私は輸入にヘッダを追加し、同じ問題を持っていたトリック(感謝Subtain Ishfaqに)

をしました"@ angle/http"から{Http、Headers}をインポートします。

関連する問題