我有一个httpclient帖子,通过一个服务,它没有给我任何错误,但它也没有把数据发布到数据库。
代码如下:
数据服务.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);
  }

}

应用组件
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网络上查过了,但是没有显示任何内容。
我该怎么解决?

最佳答案

为了提出请求,需要观察到可观察到的数据。

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

09-11 20:34