如何在typescript上实现新的字段
How on model implement new fields on typescript?
创建test.model.ts:
export interface IPosting {
text: string;
docDate: string;
isDebit: boolean;
amount: number;
debitAmount: string;
creditAmount: string;
}
export class Posting implements IPosting {
text: string;
docDate: string;
isDebit: boolean;
amount: number;
debitAmount: string;
creditAmount: string;
constructor(text: string, docDate: string, isDebit: boolean, amount: number) {
this.text = text;
this.docDate = docDate;
this.isDebit = isDebit;
this.amount = amount;
this.debitAmount = (isDebit) ? this.amount.toString() : '';
this.creditAmount = (isDebit) ? '' : this.amount.toString();
}
}
接下来,我构建服务,从请求中获取数据test.service.ts:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { IPosting, Posting } from './test.model';
@Injectable()
export class TestService {
constructor(private http: Http) {
}
getPostings(): Promise<IPosting[]> {
let token = localStorage.getItem('access_token');
let authorization = "Bearer " + token;
let headers = new Headers({ Authorization: authorization, 'X-Requested-With': 'XMLHttpRequest' });
let options = new RequestOptions({ headers: headers });
return this.http.get('/api/data', options)
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.log('Error occured: ' + error);
return Promise.reject(error.message || error);
}
}
在@Component上,我尝试从服务响应中呈现数据:
export class GLComponent implements OnInit {
private http: Http;
postings: IPosting[];
constructor(http: Http, private router: Router, private testService: TestService) {
this.postings = [];
}
ngOnInit() {
this.loadPostings();
}
loadPostings() {
this.testService.getPostings()
.then(postings => this.postings = postings)
.catch(error => {
// ...
});
}
}
然后数据显示在html上。从响应请求,我得到json只有'text', 'docDate', 'isDebit', 'amount'字段。但我需要在现有的基础上形成新的领域。
如何将您收到的元素映射到Posting
对象?
loadPostings() {
this.testService.getPostings()
.then(postings => {
this.postings = postings.map(p => {
// convert anonymous object into a Posting object
return new Posting(p.text, p.docDate, p.isDebit, p.amount);
});
)
.catch(error => {
// ...
});
}
之后,您将在this.postings
中获得Posting
对象的数组。
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- JavaScript 检查隐藏字段中的值并将其设置为隐藏字段值
- 在wordpress一定时间后更改自定义字段
- 如何在HTML输入字段中添加不可删除的后缀
- 我该如何实现CSS/HTML中使用密码字段的非常简单的文本框提示
- 如何使用输入字段、文本和提交按钮实现自定义回退功能
- 如何在文本输入字段中实现最后一个没有字母间距的字母
- JqGrid复选框字段实现失败
- 如何在Angular中实现一个可取消的可编辑字段
- Yii2实现输入字段的客户端唯一验证
- 什么才是真正的“angular”?在textarea字段上实现maxlength的方法
- 如何为多个电子邮件地址实现解析器/组件,如字段" to:"在Gmail
- 在javascript中实现搜索结果的多字段排序
- 在同一页面的多个字段上实现money.js
- 如何在typescript上实现新的字段
- 想要使用jquery实现编辑字段