What is the process of adding new fields to a model in TypeScript?

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.

Answer №1

Have you thought about transforming the data you receive into instances of the Posting class?

loadPostings() {
    this.testService.getPostings()
        .then(postings => {
          this.postings = postings.map(p => {
            // convert an anonymous object into a Posting object
            return new Posting(p.text, p.docDate, p.isDebit, p.amount);
          });
        )
        .catch(error => {
            // ...    
        });
}

Once that's done, you'll end up with an array of Posting objects stored in this.postings.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sharing the label element as a prop in React component

I encountered the following code snippet: <div className="input-field"> <label htmlFor="timeObjective">Time Objective</label> <FrequencySet label='label'/> //HERE </div> My goal is to tra ...

Error: Axios encountered an issue with resolving the address for the openapi.debank.com endpoint

After executing the ninth command to install debank-open-api, I encountered an error while running the code in my index.js file. To install debank-open-api, I used the following command: npm install debank-open-api --save Upon running the following code ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

Omit a specific page from the primary Next.js layout within the application directory

In my project, I have a main layout file located at /app/layout.tsx and separate authentication pages. I want the authentication pages to have their own custom layout defined in the file /app/auth/layout.tsx. The issue I am facing is that the main layout ...

Finding the difference or sum within an array to identify the two numbers that produce a new array

In order to clarify, I am looking for a method to identify the two smallest numbers in a sorted array that will result in a specific number when subtracted. The process can be broken down into the following steps: Iterate through the array and designate ...

Tips on accessing a browser cookie in a Next.js API endpoint

I've set a cookie in the layout.js component and it's visible in the browser. Now, I need to be able to retrieve that cookie value when a post request is made to my API and then perform some action based on that value. Despite trying different ...

"Exploring the benefits of using nested mapping for res.json() in an Express application

I have been developing an express application (server-side) that offers movie information to users, and I am attempting to send a JSON response in the following format: { "title": "Star Trek: First Contact", "year": 1996, ...

Using AngularJS for posting data without specifying a default value input may lead to unexpected results

I'm curious about why the input is not working when a default value is assigned to the controller and then posted as undefined on the server side. However, if you type directly into the input, it works fine and the value is captured. What's the d ...

Is combining AngularJS and Durandal the way to go?

Can AngularJS be integrated into a Durandal project seamlessly? Our team is currently utilizing Durandal, but we are considering transitioning to AngularJS while ensuring that the site continues to function properly. Is this a feasible undertaking and woul ...

The ng test option is failing to execute effectively

Attempting to conduct unit tests utilizing Karma and Jasmine through the ng test is proving to be a bit challenging. Upon issuing the following command: ng test --watch=false --code-coverage --main ./src/main/resources/public/scripts/xyz/workspace/commons ...

Accessing data in form rules with Vuetify: tips and tricks

Is it possible to access a data element within a rule? Click here to see my code in action I'm attempting to change the value of a data element on a text field rule within a Vuetify form. While the rule itself is functioning properly, I'm enco ...

Deciphering the concept of promises within the Node.js platform

After some research, I have come to understand that there are three main methods of calling asynchronous code: Using Events, for example request.on("event", callback); Callbacks, like fs.open(path, flags, mode, callback); Promises While browsing through ...

Mastering the integration of bootstrap datepicker - jquery plugin within AngularJS

Is it feasible to integrate this plugin into an AngularJS export table with filters, including the usage of ng-model and other functionalities? The plugin In particular, I am interested in utilizing the "range" option for selecting dates from/to. ...

What is the method to retrieve the selected value from a drop-down menu that is connected to JSON keys?

I am just starting to learn AngularJS and I need help with binding column names (keys from key-value pairs) to a select list. I want to be able to retrieve the key name when the selection in the select list is changed. The select list displays: name, snip ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...

Click on the link in the listview to close the panel

I'm currently working on a jQuery mobile page that includes a panel with a listview. Each list item has a link with a data-rel="close" attribute, and I want the panel to close whenever a list item is clicked. It's important to note that I am als ...

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

Retrieve configuration settings from a controller

https://i.sstatic.net/hUOcf.pngFor my current front end project, I am utilizing AngularJS. In order to load config values in the controller, I have tried using the standard import method. However, I keep encountering an error message: Uncaught Error: [$i ...

How can you display ng-repeat data in AngularJS when working with Laravel?

I have been attempting to display the contents of an ng-repeat, but I am facing a challenge with using double curly braces, {{ value }}. For those who have not tried this yet, let me clarify that when you use the expression {{ value }}, it will try to fin ...