【问题标题】:How to use post request correctly in Angular sending the string to json server如何在Angular中正确使用发布请求将字符串发送到json服务器
【发布时间】:2020-02-04 04:46:16
【问题描述】:

我使用json-server,我得到了类似的东西,在json 对象中我想要一个名为dates 的属性,它们是具有数字属性的对象。 我想通过post 请求日期名称添加这个json 对象及其属性; 这是json文件:

{
  "02.10.2019": {
    "301": {
      "status": "free",
      "price": 20000,
      "checkIn": "28.09.2019",
      "checkOut": "02.10.2019",
      "overallPrice": 80000
    },
    "302": {
      "status": "engaged",
      "price": 20000,
      "checkIn": "28.09.2019",
      "checkOut": "02.10.2019",
      "overallPrice": 80000
    },
    "303": {
      "status": "dirty",
      "price": 20000,
      "checkIn": "28.09.2019",
      "checkOut": "02.10.2019",
      "overallPrice": 80000
    },
    "304": {
      "status": "free",
      "price": 20000,
      "checkIn": "28.09.2019",
      "checkOut": "02.10.2019",
      "overallPrice": 80000
    }
  }
}

我只想添加带有日期名称的第二个属性,我想用函数来动态地做到这一点,它获取字符串日期,并通过httpClient 添加到json-server

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {PutNewDateService} from './put-new-date.service';

@Injectable({
  providedIn: 'root'
})
export class FirstGetService {
  constructor(private http: HttpClient, private dateNew: PutNewDateService) { }
  url1 = 'http://localhost:3000/';
  private customizing(url: string, date: string): string {
    return url + date;
  }
  getDate(date: string): Observable<{}> {
    return this.http.get(this.customizing(this.url1, date));
  }
  setDate(date: string): Observable<any> {
    return this.setGoOn(date);
    // return this.http.post(this.customizing(this.url1, date), this.dateNew.getEmptyRooms());
  }
  private setGoOn(date: string) {
    return this.http.post(this.customizing(this.url1, ''), date);
  }
  setSomething(data: string): Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'
      })
    };
    return this.http.post('http://localhost/', data, httpOptions);
  }
}

【问题讨论】:

    标签: angular json-server


    【解决方案1】:

    只需构建适当的有效负载 - 根据需要添加 mamy 属性 - 并发送它。

      setSomething(data: string): Observable<any> {
        const payload={
            somefield: somevalue,
            anotherfield:anothervalue,
            actualData:data,
        }
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  'application/json'
          })
        };
        return this.http.post('http://localhost/', payload, httpOptions);
      }
    

    现在,服务器必须接受 json 编码的消息才能正确处理此类消息,因为字面上的 payload 内容将作为请求正文发送。

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 2020-10-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多