如何在Angular中实现最简单的http发布请求?

时间:2019-04-22 11:30:52

标签: angular httpclient

正在努力获取一个简单的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

1 个答案:

答案 0 :(得分:1)

在Angular中,最佳做法是分别维护服务和组件。
如果使用angular cli,则可以通过 ng g service serviceName
生成新服务 在provider数组中的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)