Haarvey
Haarvey

Reputation: 33

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:

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'.

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.

Upvotes: 2

Views: 3857

Answers (2)

Alexandre Abrantes
Alexandre Abrantes

Reputation: 31

I had the same issue, adding Headers to the imports did the trick (thanks Subtain Ishfaq)

import {Http, Headers} from "@angular/http";

Upvotes: 3

Subtain Ishfaq
Subtain Ishfaq

Reputation: 841

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

Upvotes: 2

Related Questions