我正在学习角度2,现在我正在创建一个像在线机票预订这样的自学教学项目。在那,我有一个屏幕预订 新票。我已经配置了JSon-server mock来获取和发布 我申请的数据。
我有一项服务来获取和发布数据,如下所示
import { Injectable, OnInit, Inject } from '@angular/core'
import { Http, Response, Headers, RequestOptions } from '@angular/http'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/do';
import {Observable} from 'rxjs/Rx';
import { UserInfo } from './userInfo.model'
import { DataModel } from './data.model'
Injectable()
export class UserInfoService implements OnInit {
userInfo: UserInfo;
dataModel: DataModel;
constructor( @Inject(Http) private _http: Http) {
this.userInfo = new UserInfo();
this.dataModel = new DataModel();
}
setUserInfo(userName: string, loggedIn: boolean, action: string): UserInfo {
this.userInfo.userName = userName;
this.userInfo.isLoggedIn = loggedIn;
this.userInfo.process = action;
return this.userInfo;
}
setProcess(action: string) {
this.userInfo.process = action;
}
getUserInfo(): UserInfo {
return this.userInfo;
}
fetchJSONdata(requiredType: string) {
console.log('param' + requiredType);
return this._http.get("http://localhost:3000/" + requiredType).map((res: Response) => <DataModel[]>res.json())
.do(data => console.log(requiredType + '-> Retrive Data:' + JSON.stringify(data)));
}
// Passing requiredType as "bookings"
**pushJSONData**(requiredType: string, _dataModel: DataModel) {
let bodyString = JSON.stringify(_dataModel); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post("http://localhost:3000/" + requiredType, _dataModel, options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error')).do(data => console.log(data));
}
ngOnInit() {
}
}
这是我的数据模型
export class DataModel {
userid : string;
password:string;
mail: string;
city: string;
address: string;
from: string;
to: string;
date:Date;
transportname:string;
pnr: string;
tickets: string;
about: string;
name: string;
company: string;
phonenumber: string;
rule:string;
faq:string
}
我从屏幕传来的数据是
DataModel {from: "ssssss", to: "dddddd", date: "2017-06-08", transportname: "fffffff", tickets: "gggggggggg"…}
来自网址[http://localhost:3000/bookings][1]
中的JSON-Server模拟的数据[
{
"from": "",
"to": "",
"transportname": "Ng-Travels",
"pnr": "",
"tickets": "",
"date": ""
}
]
最后是我的DB.json文件
"bookings": [
{
"from": "",
"to": "",
"transportname": "Ng-Travels",
"pnr": "",
"tickets": "",
"date": ""
}
]
我的问题是,当我尝试使用 UserInfoService 类中的 pushJSONData 函数发布数据时(请查看此问题的第一部分),我没看到任何东西。数据没有在db.json文件中更新,甚至我没有在控制台中看到任何错误。请帮助纠正这个问题。所以我可以继续学习。
提前致谢
由于 马尼万南