Execution issue with Typescript function

In my Nativescript project, I have the following TypeScript file:

import { Observable } from 'tns-core-modules/data/observable';
import { isIOS } from "tns-core-modules/platform";
import { Color } from "tns-core-modules/color";
import { request, getFile, getImage, getJSON, getString } from "tns-core-modules/http";

export class HomeViewModel extends Observable {

    items: {
        name: string,
        desc: string, 
        price: string, 
        imageSrc: string, 
     }[];

    getData = getJSON("http://localhost:3000/items").then((r: any) => {
        this.getData = r; // Assign data from response on success
            console.log("blarg!!!")
        }, (e) => {
    }); 

    onItemLoading(args) {
        if (isIOS) {
            var newcolor = new Color("#e6e6e6");
            args.ios.backgroundView.backgroundColor = newcolor.ios;
        }
    }

    constructor() {
        super();
    }
}

I am facing an issue where the getData function is not being called or executed. How can I trigger the execution of getData function?

Answer №1

It appears that the current code is not very type-safe and may lead to unintended consequences.

getData = getJSON("http://localhost:3000/items").then((r: any) => {
    this.getData = r; // assigning it from the response upon success
        console.log("blarg!!!")
    }, (e) => {
}); 

If you declare the type in the initial assignment, it would look like this:

getData: Promise<void> = ...

If you specify the type in the inner assignment, it would be:

this.getData = r as any;

The above solutions might not achieve the desired functionality. Perhaps a better approach would be:

data: any;

constructor() {
    super();

    getJSON("http://localhost:3000/items").then((r: any) => {
        this.data = r; // assign it from the response when successful
            console.log("blarg!!!")
        }, (e) => {
    });
}

Answer №2

To achieve the desired outcome, consider invoking it at a higher level within the stack. Alternatively, if you wish for getData to execute upon object creation, ensure that getData() is called in your constructor function.

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

Linking key value pairs through a TypeScript interface

coding interface StoreActions { setUserName: string actionOne: string[] actionTwo: { testValue: string } } interface CustomActions extends AnyAction { typeOfAction: keyof StoreActions // additionalData:??? } The attribute typ ...

AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online. However, I am facing an issue where clicking on an icon does not update the ng-mode ...

Error message in Typescript with React: "The type 'ComponentClass<StyledComponentProps<{}>>' cannot be assigned to type 'typeof MyComponent'"

Currently experimenting with integrating the Material UI 1.0 (beta) @withStyles annotation into a React component. The documentation provides a JavaScript example (), however, it results in a compilation error when using Typescript. Despite the error, the ...

Connecting Ionic 3 with Android native code: A step-by-step guide

I just finished going through the tutorial on helpstack.io and was able to successfully set up the HelpStackExample with android native based on the instructions provided in the GitHub repository. The only issue is that my company project uses Ionic 3. H ...

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

How to Utilize Knockout's BindingHandler to Integrate JQuery.Datatables Select Feature?

I've developed a custom KO bindingHandler (view it here) to assist in updating the DataTable. The documentation for JQuery.DataTable.Select regarding how to access data requires a handle. You can see the details here. var table = $('#myTable&a ...

Navigating through multiple pages using an Observable in Angular

After countless attempts, I still haven't been able to figure it out. Any assistance would be greatly appreciated; I recently came across Angular and RxJs. The issue I'm facing involves a service that fetches resources from various URLs of the s ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

Access-Control-Allow-Origin header not being sent by ExpressJS

In the midst of my project, I find myself needing an angular web application to connect with a node/express backend. Despite trying to implement Cors for this purpose, the express server refuses to send the Access-Control-Allow-Origin header. I am perplexe ...

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...

What is the process of overriding a method from an abstract class that employs generics for typing?

In my quest to develop an abstract class with an abstract static method, I find myself wanting to override this method in a concrete class. The static nature of the method stems from its responsibility to create a 'copy' from a database model and ...

Conditional type in Typescript can be used to infer tuple types

Why are output1 and output2 not both inferred as [number, number, number] in the following code snippets? Snippet 1 : type InferTuple1<T> = T extends any[] ? [...T]: never; const func1 = <T>(t: InferTuple1<T>) => t; const output1 = ...

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

Learn how to use JavaScript to parse binary files

Is there a way to interpret this binary data below? Binary2 { sub_type: 0, buffer: Buffer(16) [ 12, 15, 64, 88, 174, 93, 16, 250, 162, 5, 122, 223, 16, 98, 207, 68 ], position: 16 } I've attempted different methods like using ...

Creating a numeric sequence based on the date of a corresponding transaction - a step-by-step guide

INTRO I built an e-commerce app with TypeScript and Sequelize ORM. In the app, I have a table that generates sequential invoice numbers based on the current day. CREATE TABLE `dm_generate_trx` ( `id` int NOT NULL AUTO_INCREMENT, `date` date NOT NULL, ...

Troubleshooting React child problems in TypeScript

I am facing a coding issue and have provided all the necessary code for reference. Despite trying numerous solutions, I am still unable to resolve it. export class JobBuilderOptimise extends React.Component<JobBuilderOptimiseProps & JobBuilderOptim ...

Error: The TypeScript aliases defined in tsconfig.json cannot be located

Having trouble finding the user-defined paths in tsconfig.json – TypeScript keeps throwing errors... Tried resetting the entire project, using default ts configs, double-checked all settings, and made sure everything was up-to-date. But still no luck. H ...

My app is having trouble updating routes correctly. Can anyone provide guidance on how to configure routeConfig properly for my application?

I'm facing an issue with my angular 2 typescript app component routes not working properly. Whenever I try to change the route to login in the address bar, it fails to load the corresponding HTML content. Strangely, there are no console errors displa ...

What does Angular 5 offer in terms of functionality that is equivalent to?

I am working on my AngularJS 1.5 application where I have controllers directly calling service functions. What is the recommended approach to achieve this in Angular? $scope.permissions = ClockingMenuService.permissions; $scope.data = ClockingMenuService ...

The TypeScript error is causing issues in the Express router file

Here is the structure of my module: import * as express from 'express'; let router = express.Router(); router.post('/foo', function(req,res,next){ // ... }); export = router; However, I'm encountering the following error: ...