How can I call a method from a class using Typescript when getting an error saying that the property does not exist on the

Below is a service definition:

export class MyService {
    doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) {
        // Function performs an action
    }
}

This service is utilized in a component as shown below:

export class MyComponent implements OnInit {
    someFunction(): void { 
        this.myService.doSomething(
            {
                onSuccess(data: Object) {
                    onSuccessFunction(data) // Error occurs here
                },
                onError(err: any) {
                }
            }
        )
    }
    
    onSuccessFunction(data: Object) {
    }
}

In the code snippet above, onSuccessFunction is defined within MyComponent and called inside the anonymous function onSuccess. However, TypeScript is throwing the following error message:

Property 'initActiveOrders' does not exist on type '{ onSuccess: (data: Object) => any; onError: (err: HttpErrorResponse) => any; }'.ts(2339)

What could be the possible reason behind this error?

Answer №1

Implementing an arrow function is the way to go:

newFunction(): void { 
  this.myService.doSomething({
    onSuccess: (data: Object) => {
      this.onSuccessHandler(data);
    },
    ...
  });
}

Answer №2

Don't forget to include this. before calling the method on line 5

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

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

The inclusion of routes from an API request in Angular does not seem to be functioning properly when

Currently, I am embarking on a project that requires the loading of specific routes from a CMS using an API request. Upon executing the code snippet below with "ng serve -o," all routes function properly; however, once I run "npm serve:ssr" following a bu ...

Can we categorize various types by examining the characteristics of an object?

Is it feasible with TypeScript to deduce the result below from the given data: const data = { field1: {values: ['a', 'b', 'c']}, field2: {values: ['c', 'd', 'e'], multiple: true} } const fiel ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...

Ways to reload a page in Angular using routerLink and ID

I am working on an Angular application that involves navigation using routerlinks. My goal is to navigate to a specific user page by ID if the page is already open and meets certain conditions. In my .component.ts file, I have the following code snippet: ...

What is the process for subscribing to the output of a flatMap operation?

Is there a way to subscribe to the result of flatMap in this code block? timer(0, 2000) .pipe( flatMap(() => this.scannerService.scan(this.scanType)), takeWhile(res => res.errorDesc !== "SUCCESS") ) .subscrib ...

The 'data-intro' property cannot be bound to the button element as it is not recognized as a valid property

I've been using the intro.js library in Angular 8 and so far everything has been working smoothly. However, I've hit a roadblock on this particular step. I'm struggling to bind a value in the data-intro attribute of this button tag. The text ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

The React component using createPortal and having its state managed by its parent will remain static and not refresh upon state modifications

I am facing a problem that can be seen in this live example: https://stackblitz.com/edit/stackblitz-starters-qcvjsz?file=src%2FApp.tsx The issue arises when I pass a list of options to a radio button list, along with the state and setter to a child compon ...

What is the best way to simulate updating an object within an array for unit testing in Angular?

Currently, I am in the process of testing my Redux reducers. So far, I have successfully tested the GET and CREATE functionalities but I'm facing a challenge with implementing the UPDATE functionality. I am unsure how to mock it effectively. Below, yo ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

What sets apart the typescript@latest and typescript@next NPM packages from each other?

Can you enlighten me on the disparities between typescript@next and typescript@latest? I understand the functionality of typescript@next, yet I struggle to differentiate it from typescript@latest. From my perspective, they appear to be identical. There is ...

Warning in VSCODE: Use caution when using experimental decorators

I have been working on an Angular2-Typescript application and created the project using angular-cli with the command: ng new myApp However, I am facing a warning issue when creating a new component with the @Component tag. I have tried to resolve this p ...

Notifying child components of data changes in Angular 2

Within my Angular 2 application, I have a primary component that contains a specific child component called SystemDynamicsComponent. To include this child component within the parent component, I use the following syntax: <system-dynamics [sdFactors]= ...

Verify if the Contact Number and Email provided are legitimate

Is it possible to determine if the phone number or email entered by a user is valid or not? Using Angular 7 and Firebase? ...

An unusual occurrence of events may occur when serverTimestamp fields are added to a Firestore collection alongside new elements

I've developed a web application where users can share messages on a specific topic. I'm utilizing Firebase as the backend with data stored in Firestore. Each message object contains an ID, content, creation timestamp, and last updated timestamp. ...

Is there a way to search for text and highlight it within an HTML string using Ionic

Welcome everyone! I am currently utilizing Ionic to load an article from a local HTML string. <ion-content padding> <p [innerHTML]="url"></p> </ion-content> The 'url' variable contains the local HTML string. My goal ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...