typescript Angular 5 - HttpClient Post 未发布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48458343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:11:44  来源:igfitidea点击:

Angular 5 - HttpClient Post not posting

angulartypescriptangular5

提问by

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.

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

Here is the code:

这是代码:

dataService.ts

数据服务.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

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

最后是 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?

我已经在 chrome 网络上检查过帖子,但那里没有显示任何内容。我怎样才能解决这个问题?

回答by

Observables need to be observed to make a request.

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

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

回答by Reshan Pubudu

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

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

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

    return this.http.post('http://myurl/index.php', body, httpOptions);
}

回答by Niran Manandhar

let params = new HttpParams()
params=params.set('firstName', 'Joele');
params=params.set('lastName', 'Smith4');

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