如何在typescript上实现新的字段

How on model implement new fields on typescript?

本文关键字:字段 实现 typescript      更新时间:2023-09-26

创建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对象的数组。