尝试从'@ angular / common / http'导入import {HttpClient,Headers,RequestOptions};

时间:2019-10-17 11:42:45

标签: angular ionic-framework

我正在与ionic 4项目合作。现在我正在尝试发布http帖子,并且正在关注此链接https://www.techiediaries.com/ionic-http-post/上的内容。现在说他无法在@ angular / common / http'中找到Header,RequestOptions;

我尝试了在堆栈溢出时发现的其他问题。

import { Component, OnInit } from '@angular/core';
import { HttpClient, Headers, RequestOptions } from 
'@angular/common/http';

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

constructor(public httpClient: HttpClient) {
 }
 ngOnInit(){}

  sendPostRequest() {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
const requestOptions = new RequestOptions({ headers: headers });

let postData = {
        "name": "Customer004",
        "email": "customer004@email.com",
        "tel": "0000252525"
}

this.http.post("http://127.0.0.1:3000/customers", postData, requestOptions)
  .subscribe(data => {
    console.log(data['_body']);
   }, error => {
    console.log(error);
  });
  }

4 个答案:

答案 0 :(得分:0)

嗨,尝试使用HttpHeaders插入此标头:

import { HttpClient, HttpHeaders , RequestOptions } from '@angular/common/http';

答案 1 :(得分:0)

这是我们可以添加标题的方法

  import { HttpHeaders } from '@angular/common/http';


    let yourheaders = new HttpHeaders({
    'Content-Type': 'application/json'
    });

    let youroptions = {
    headers: yourheaders
    }

看看this 看看this also

答案 2 :(得分:0)

保持简单:

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { 
}

获取Api:

this.http.get('https://someapi.com/posts').subscribe((response) => {
    console.log(response);
});

张贴Api:

    let YourHeaders = {'Content-Type':'application/json'};
    this.http.post(url, YourData, {headers: YourHeaders})
      .subscribe(data => {
      console.log(data)
    },
    (error) => {
            console.log("Error" + error)
    })

答案 3 :(得分:0)

从5角度开始,如果仅想在JSON中进行通信,则不需要将Content-Type设置为application/json。它将默认以JSON格式进行通信。

因此您可以将其用作

用于GET通话

this.http.get('YOUR API').subscribe((response) => {
    console.log(response);
});

用于POST呼叫

this.http.post('YOUR API', `{JSON OBJECT}`).subscribe((response) => {
    console.log(response);
});

您还可以如下添加自定义标题(例如,授权令牌)

import { HttpClient, HttpHeaders } from '@angular/common/http';

requestHeaders = new HttpHeaders().set('Authorization', 'Token');

并按如下所示使用它

用于GET通话

this.http.get('YOUR API', {headers: this.requestHeaders}).subscribe((response) => {
    console.log(response);
});

用于POST呼叫

this.http.post('YOUR API', `{JSON OBJECT}`, {headers: this.requestHeaders}).subscribe((response) => {
    console.log(response);
});

HttpHeaders包括set()append()等方法。