【问题标题】:Angular 5 - HttpClient Post not postingAngular 5 - HttpClient Post 未发布
【发布时间】:2018-07-05 14:45:57
【问题描述】:

我有一个通过服务发布的 httpClient 帖子,它没有给我任何错误,但也没有将数据发布到数据库中。

代码如下:

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 网络上查看了该帖子,但那里没有显示任何内容。 我该如何解决这个问题?

【问题讨论】:

标签: angular typescript angular5


【解决方案1】:

需要观察 Observable 才能发出请求。

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

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,我就这样使用(使用 FormData)。试试吧。它对我有用。

    insertData() {
        let body = new FormData();
        body.append('firstName', 'Joele');
        body.append('lastName', 'Smith4');
    
        return this.http.post('http://myurl/index.php', body, httpOptions);
    }
    

    【讨论】:

      【解决方案3】:
      let params = new HttpParams()
      params=params.set('firstName', 'Joele');
      params=params.set('lastName', 'Smith4');
      
      this.http.post('http://myurl/index.php', params , httpOptions);
      

      【讨论】:

      • 您能解释一下为什么这是一个解决方案以及它是如何解决问题的吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2018-08-07
      相关资源
      最近更新 更多