如何通过发送post请求替换JSON数据。目前,该数据正在附加到现有数据
我对Angular2很陌生,面临着与RestAPI有关的问题。我向位于JSON文件的服务器发送post请求。我想替换JSON文件中的现有数据,但结果是,我收到了追加数据。 这是我的代码:如何通过发送post请求替换JSON数据。目前,该数据正在附加到现有数据,json,angular,typescript,Json,Angular,Typescript,我对Angular2很陌生,面临着与RestAPI有关的问题。我向位于JSON文件的服务器发送post请求。我想替换JSON文件中的现有数据,但结果是,我收到了追加数据。 这是我的代码: let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); this.http.post(url, bod
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options).map((res:Response) => res.json())
.subscribe((body) => body );
我的JSON文件是:
{
"budget": [
{
"service": "electricity",
"real_amount": 100,
"expected_amount": 100,
"id": 0
}
]
}
在发送了and post请求之后,我的JSON文件开始被删除
{
"budger":
{
"service": "electricity",
"real_amount": 100,
"expected_amount": 100,
"id": 0
}
],
{
"service": "electricity",
"real_amount": 100,
"expected_amount": 100,
"id": 0
}
]
}
我的ts文件:
import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import {Http, Headers,RequestOptions,Response} from
'@angular/http';
import {ApiService} from './api.service';
import { URLSearchParams } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
real_amount: string;
service: string;
expected_amount: string;
public data;
public real_data;
constructor(private http: Http) {
}
ngOnInit(): void {
this.http.get("./assets/data/expected_expensives.json")
.subscribe((data) => {
this.data = data.json();
console.log(data.json());
});
}
updateBudget() {
console.log(this.service +" " + this.real_amount);
console.log(this.data.budget.length);
for(let i=0 ; i< this.data.budget.length; i++)
{
if (this.data.budget[i].service === this.service)
{
console.log(this.data.budget[i].service);
this.data.budget[i].real_amount=this.real_amount;
}
}
let body:any = JSON.stringify(this.data.budget);
let url = "http://localhost:3000/budget";
let response:any;
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options).map((res:Response) => res.json())
.subscribe((body) => body );
}
}
从'@angular/core'导入{Component,OnInit};
导入'rxjs/add/operator/map';
从“@angular/core”导入{Injectable};
从导入{Http,Headers,RequestOptions,Response}
“@angular/http”;
从“/api.service”导入{ApiService};
从“@angular/http”导入{URLSearchParams};
@组成部分({
选择器:'应用程序根',
templateUrl:“./app.component.html”,
样式URL:['./app.component.scss']
})
导出类AppComponent实现OnInit{
实际金额:字符串;
服务:字符串;
预期金额:字符串;
公共数据;
公共真实数据;
构造函数(专用http:http){
}
ngOnInit():void{
this.http.get(“./assets/data/expected\u expensives.json”)
.订阅((数据)=>{
this.data=data.json();
log(data.json());
});
}
updateBudget(){
console.log(this.service+“”+this.real\u amount);
log(this.data.budget.length);
for(设i=0;ires.json())
.订阅((正文)=>正文);
}
}
我的html文件:
<div id="main">
<div id="right_side">
<div class="form-group row">
<label>Choose a service</label>
<select [(ngModel)]="service">
<option *ngFor="let item of data?.budget"
ngDefaultControl >{{item.service}}</option>
</select>
<label>Enter an amount</label>
<input id="real_amount" type="text"
[(ngModel)]="real_amount" ngDefaultControl>
<input type="submit" value="Pay"
(click)="updateBudget(service,real_amount)">
</div>
</div>
<div id="left_side">
<table>
<thead>
<th>Service</th>
<th>Expected Expencies</th>
<th>Real Expencies</th>
</thead>
<tbody>
<tr *ngFor="let item of data?.budget">
<td>{{item.service}}</td>
<td>{{item.expected_amount}}</td>
<td>{{item.real_amount}}</td>
</tr>
</tbody>
</table>
</div>
</div>
选择服务
{{item.service}}
输入金额
服务
预期费用
实际费用
{{item.service}}
{{项目.预期金额}
{{item.real{u amount}}
有人能提出适当的解决办法吗?
问候。service.ts
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Response,RequestOptions,Headers};
从“rxjs/Observable”导入{Observable};
导入'rxjs/add/operator/map';
导入“rxjs/add/operator/catch”;
导入“rxjs/add/observable/throw”;
导出类CcDataServiceService{
构造函数(专用http:http){
}
getLocalData():可观察{
返回此.http.get('assets/data/expected\u expensives.json'))
.map(此.extractData)
.接住(这个.把手错误);
}
getserverData(ajaxdata):可观察{
log('ajaxdata::'+JSON.stringify(ajaxdata));
let headers=新的头({'Content-Type':'application/json'});
let options=newrequestoptions({headers:headers});
返回此.http.post(url,ajaxdata)
.map(此.extractData)
.接住(这个.把手错误);
}
私有数据(res:Response){
const body=res.json();
返回体| |[];
}
私有句柄错误(错误:任意){
const errMsg=(error.message)?error.message:
error.status?`${error.status}-${error.statusText}`:'服务器错误';
控制台错误(errMsg);
log('Server Error!');
返回可观察抛出(errMsg);
}
}
组件技术
构造函数(公共jsonDataService:CCDATASERVICE){
}
恩戈尼尼特(){
设thisx=this;
//如果要从服务器获取数据,请调用getserverData(),否则调用getLocalData()
这是.jsonDataService.getserverData().subscribe(
功能(成功){
thisx.data=成功;
thisx.datahandle(成功);
},
error=>console.log('获取服务器数据错误:'+JSON.stringify(错误));
}
数据句柄(jsonData){
console.log('check your data'+JSON.stringify(jsonData));JSON文件中的现有数据位于何处?为了澄清问题,请将您的ts和服务的一些代码放入其中。我使用JSON服务器,我的JSON.file位于package.JSON所在的同一位置。(根文件夹)。我使用假的服务器。你想替换项目中JSON文件中的现有数据吗?但是为什么?替换意味着什么?我在网页上显示JSON文件中的一些数据,我会更新它。但是我的更新只在网页上,所以要在本地更新数据,我必须发送post请求,以便在文件上进行更新。也许我犯了错误?什么我得到的是,您已经在您的网页(模板)上显示了来自本地json文件(可能在资产文件夹中)的一些数据。现在,您希望通过服务的“post”ajax调用更新您的网页(html模板),并且不再需要本地json数据。我说的对吗?非常感谢,Ahmad。很高兴,这对您有所帮助。如果有帮助,请接受它作为答案。
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export class CcDataServiceService {
constructor(private http: Http) {
}
getLocalData(): Observable<any[]> {
return this.http.get('assets/data/expected_expensives.json')
.map(this.extractData)
.catch(this.handleError);
}
getserverData(ajaxdata): Observable<any[]> {
console.log('ajaxdata::' + JSON.stringify(ajaxdata));
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(url, ajaxdata)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
console.log('Server Error!');
return Observable.throw(errMsg);
}
}
constructor(public jsonDataService: CcDataServiceService) {
}
ngOnInit() {
let thisx = this;
// if you want data from server call getserverData() else getLocalData()
this.jsonDataService.getserverData().subscribe(
function (success) {
thisx.data = success;
thisx.datahandle(success);
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
}
datahandle(jsonData){
console.log('check your data' + JSON.stringify(jsonData)); <-----check data
// may parse your data
let keys = Object.keys(jsonData);
console.log(keys);
}