I have created a test.model.ts file:
export interface ITransaction {
description: string;
transactionDate: string;
isDebit: boolean;
amount: number;
debitAmount: string;
creditAmount: string;
}
export class Transaction implements ITransaction {
description: string;
transactionDate: string;
isDebit: boolean;
amount: number;
debitAmount: string;
creditAmount: string;
constructor(description: string, transactionDate: string, isDebit: boolean, amount: number) {
this.description = description;
this.transactionDate = transactionDate;
this.isDebit = isDebit;
this.amount = amount;
this.debitAmount = (isDebit) ? this.amount.toString() : '';
this.creditAmount = (isDebit) ? '' : this.amount.toString();
}
}
Next step is to create a service that fetches data from the endpoint in test.service.ts:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { ITransaction, Transaction } from './test.model';
@Injectable()
export class TestService {
constructor(private http: Http) {
}
getTransactions(): Promise<ITransaction[]> {
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('An error occurred: ' + error);
return Promise.reject(error.message || error);
}
}
In the @Component, I am attempting to display data from the service response:
export class GLComponent implements OnInit {
private http: Http;
transactions: ITransaction[];
constructor(http: Http, private router: Router, private testService: TestService) {
this.transactions = [];
}
ngOnInit() {
this.loadTransactions();
}
loadTransactions() {
this.testService.getTransactions()
.then(transactions => this.transactions = transactions)
.catch(error => {
// ...
});
}
}
The JSON response from the request only includes 'description', 'transactionDate', 'isDebit', and 'amount' fields. However, I require additional fields in the model based on the existing ones. The current code is not functioning as expected.