Ionic 3: Header is not assigned value

this is my code

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

import 'rxjs/add/operator/map';
import { Headers } from '@angular/http';

@Injectable()
export class DataproviderProvider {

  constructor(public http: HttpClient) {
    console.log('Hello DataproviderProvider Provider');
  }

  // registering the user
  resgisterData(registerdata) {
    let headers = new Headers({'Content-Type': 'application/json'});
    this.http.post('http://localhost:3000/api/contact',registerdata,{headers: headers})
    .map(res => res.json());

  }
}

I’m getting error like

Argument of type ‘{ headers: Headers; }’ is not assignable to parameter of type ‘{ headers?: HttpHeaders | { [header: string]: string | string; }; observe?: “body”; params?: Ht…’. Types of property ‘headers’ are incompatible. Type ‘Headers’ is not assignable to type ‘HttpHeaders | { [header: string]: string | string; }’. Type ‘Headers’ is not assignable to type ‘{ [header: string]: string | string; }’. Index signature is missing in type ‘Headers’.

In visual studio code, it is displaying error at {headers: headers}

Use HttpHeaders instead Headers;

let headers = new **HttpHeaders**({'Content-Type': 'application/json'});
1 Like

Don’t bother with headers at all. What you do want to do is define a business model interface and use it:

interface RegistrationRequest {
 // stuff goes here
}

interface RegistrationResponse {
  // other stuff goes here
}

registerUser(regfood: RegistrationRequest): Observable<RegistrationResponse> {
  return this.http.post<RegistrationResponse>(api, regfood);
}

Always type all method arguments and return values. It makes your code self-documenting and easier to read, and helps the build tools and your development environment help you avoid silly bugs.