我有一个 httpClient post,通过一个服务,它没有给我任何错误,但它也没有将数据发布到数据库。
代码如下:
数据服务.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);
}
}
应用程序组件.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 网络上查看了帖子,但那里没有显示任何内容。 我该如何解决这个问题?
最佳答案
Observable 需要被观察才能发出请求。
myInsert() {
this.dataService.insertData().subscribe(
response => console.log(response),
err => console.log(err)
);
}
关于Angular 5 - HttpClient Post 不发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48458343/