POST data http


#1

I’m trying post data

postData(params, data) {
    console.log(data);
    let headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
    return this.http.post(this.api + data, JSON.stringify(params), {
      headers: headers,
      method: 'POST'     --> error
    }).map(
      (res: Response) => { return res.json(); }
    );
  }
  }

but I get this error
Argument of type ‘{ headers: HttpHeaders; method: string; }’ is not assignable to parameter of type ‘{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: “body”; params?: Ht…’.at line 27 col 7

I imported the followings packages

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Headers, Http, Response, RequestOptions } from '@angular/http';

#2

I use this for my network communication for example:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

private headers = new Headers({ 'Content-Type': 'application/json' });

 async createUserProfile(token: string, userId: string, displayName: string, secret: string, online: boolean, status: string): Promise<Profile> {
    try {
      let headers = new Headers({ 'Content-Type': 'application/json', 'x-auth': token });
      const response = await this.http.post(`${this.server}${this.profilesRoute}`, JSON.stringify({ userId, displayName, secret, online, status }), { headers: headers }).toPromise();
      this.userProfile = response.json();
      return this.userProfile;
    } catch (err) {
      throw new Error(err.status + " - " + err.statusText);
    }
  }

Perhaps this code snippet helps you.


#3

thks friend @Jacktoolsnet but what is correct to use Headers or HttpHeaders
I"ll teste your code to return feedback


#4

Correct is what works :slight_smile: