如何在Angular中提供最简单的http post请求?

问题描述 投票:-1回答:1

为了获得一个简单的http帖子而苦苦挣扎,这里是我的代码:

var config = {
      headers : {
          'Content-Type': 'application/json'
      }
    }

    var data = {
      "gender":"M"
    };

    this.http.post<any>("http://localhost:8080/rest/endpoint", JSON.stringify(data), config)
    .subscribe(
        (val) => {
            console.log("POST call successful value returned in body", 
                        val);
        },
        response => {
            console.log("POST call in error", response);
        },
        () => {
            console.log("The POST observable is now completed.");
        }
    );
  }

通过单击按钮调用此请求,执行后我可以在Chrome网络选项卡中看到已执行OPTIONS http请求,返回GET,HEAD,POST,PUT,DELETE,OPTIONS,然后执行POST,但它似乎没有发送我打算发送的正文数据,下面是我在网络标签中看到的:

**General**
Request URL: http://localhost:8080/rest/endpoint
Request Method: OPTIONS
Status Code: 200 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
**Response Headers:**
Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS
Content-Length: 0
Date: Mon, 22 Apr 2019 11:18:51 GMT
**Request Headers:**
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Mobile Safari/537.36
angular httpclient
1个回答
1
投票

在Angular中,最佳实践是分别维护服务和组件。 如果使用angular cli,您可以通过ng g service serviceName生成新服务 向提供者数组中的appmodule(根模块)添加/包含服务,以使其可全局访问。您可以通过将服务包含在特定的component.ts文件中来使服务本地化。 我会为您提供基本的展望/工作。在service.ts中导入必要的模块。

import { Injectable } from '@angular/core'; 
import { HttpClient, HttpParams, HttpErrorResponse } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
  providedIn: 'root'
})
export class serviceName {
  private url = `http://localhost:8080/rest/endpoint`
  constructor(private http: HttpClient) { }

  //method 
  public newGender(data): Observable<any> {
    const params = new HttpParams()
      .set('gender', data.gender)
    return this.http.post(`${this.url}`, params)
  }

在component.ts中

constructor(service:serviceName){}
//subscribe to service now
//method
public methodName=()=>{
   let data = {
      "gender":"M"
    };
this.service.newGender(data).susbcribe(
response=>{
//your response
})
} //end method (call this method if needed)
© www.soinside.com 2019 - 2024. All rights reserved.