首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Angular中正确使用post请求将字符串发送到json服务器

如何在Angular中正确使用post请求将字符串发送到json服务器
EN

Stack Overflow用户
提问于 2019-10-07 02:39:58
回答 1查看 461关注 0票数 0

我使用json-server,我得到了类似的东西,在json object中,我想有一个名为dates的属性,它是具有number属性的对象。我想按post请求日期名称及其属性添加到此json对象中;下面是json-file:

代码语言:javascript
复制
{
  "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
    }
  }
}

我只想用date name添加第二个属性,我想用funtion来做这件事,它得到字符串date,然后按httpClient添加到json-server中。

代码语言:javascript
复制
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);
  }
}
EN

回答 1

Stack Overflow用户

发布于 2019-10-08 01:00:10

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

代码语言:javascript
复制
  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内容将作为请求正文发送。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58260229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档