16

I have a httpClient post, through a service, that's not giving my any errors but it's not posting the data to the database either.

Here is the code:

dataService.ts

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

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class DataService {

  constructor(private http: HttpClient) {}

  insertData() {
    const body = JSON.stringify({firstName: 'Joele', lastName: 'Smith4'});
    return this.http.post('http://myurl/index.php', body, httpOptions);
  }

}

app.component.ts

import { Component } from '@angular/core';
import { DataService } from './services/data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(private dataService: DataService) {}

  myInsert() {
    if (this.dataService.insertData()) {
      alert('Data Inserted Successfully');
    }

  }

}

and finally app.component.html

<div (click)="myInsert()">Click Me</div>

I've checked on chrome network for the post but nothing is shown there. How can I fix this?

  • 4
    Possible duplicate of [Angular 2 http.post() is not sending the request](https://stackoverflow.com/questions/36208732/angular-2-http-post-is-not-sending-the-request) – JB Nizet Jan 26 '18 at 09:07

3 Answers3

51

Observables need to be observed to make a request.

myInsert() {
  this.dataService.insertData().subscribe(
    response => console.log(response),
    err => console.log(err)
  );
}
2

I had same problem and i used like this(using FormData).try it. It work for me.

insertData() {
    let body = new FormData();
    body.append('firstName', 'Joele');
    body.append('lastName', 'Smith4');

    return this.http.post('http://myurl/index.php', body, httpOptions);
}
lt.price
  • 79
  • 1
  • 7
0
let params = new HttpParams()
params=params.set('firstName', 'Joele');
params=params.set('lastName', 'Smith4');

this.http.post('http://myurl/index.php', params , httpOptions);
Niran Manandhar
  • 1,097
  • 8
  • 8