Angular 5 - HttpClient Post 未发布

Angular 5 - HttpClient Post not posting

我有一个 httpClient post,通过一项服务,它没有给我任何错误,但它也没有 post 将数据发送到数据库。

代码如下:

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

  }

}

最后 app.component.html

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

我已经在 chrome 网络上检查了 post,但那里没有显示任何内容。 我该如何解决这个问题?

Observables需要被观察才能发出请求。

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

我有同样的问题,我是这样使用的(使用 FormData)。试试吧。它对我有用。

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

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

this.http.post('http://myurl/index.php', params , httpOptions);