invoking a function within an object in Typescript

 export class MockedDataService {
    constructor(private Session: SessionService) {}

    private getMockedResponse(name:string){
       return ""; // placeholder for the response data, will be a promise
    }


    public mocked:{
           products:{
              getAllProducts: function(){return this.getMockedResponse("")},
              getProductByType: function(type){return this.getMockedResponse(type)}
           }

    }
}

If you inject this class into a component, you can use it like this:

this.MockedDataService.mocked.products.getAllProducts().then((result) => { 
  console.log(result);
}).catch((err) => {
  console.log("error: ", err.message);        
});  

An error may occur: "this.getMockedResponse is not a function" To address this issue, modify the code to :

getAllProducts: function(){return ()=> this.getMockedResponse("")}

However, changing it in this way might result in another error: "this.MockedDataService.mocked.products.getAllProducts().then is not a function"

Answer №1

Once you assign

getAllProducts: function(){return this.getMocked("")}
, you lose your context.

To maintain the context, either use an arrow function at a higher level or explicitly bind it.

getAllProducts: () => { return this.getMocked(""); }

Alternatively, you can simplify it to:

getAllProducts: () => this.getMocked("")

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

The initial Get request does not receive data upon first attempt

In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once ...

Rollup ESM creates faulty imports

I need to package a TypeScript React app as a component in an ES module or UMD, but the ES bundle generated is producing an invalid JS module. When bundling, I receive the following hints. However, I am unable to find a solution for this. (!) Missing glob ...

What is preventing me from executing the "npm update" command in my Ionic project?

I am having trouble running the npm update or npm install command in my ionic project and I keep getting an error message. Additionally, here is the output of my "ionic info" command: ...

The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcomin ...

Is there a way to apply Validators.required just once for all required form fields in a Reactive Form?

Latest version of Angular is 4.4.3. In Reactive Form, you can use Validators.required for each form field as shown below: this.loginForm = this.fb.group({ firstName: ['', [Validators.required, Validators.maxLength(55)]], ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

Typescript/Three.js encounters the issue of game objects becoming undefined

Something in my code seems to have broken unexpectedly. I can't figure out why the "Game" object is defined before calling this.render() in the constructor, but becomes undefined in the render method. Before render(), the console shows: Game camera: ...

How can I use JavaScript to update the content inside HTML tags with a specific string?

I have a situation where I need to replace a string in two different ways Input: Parameters-->string, AnnotationName, input Case 1: And I should input <i>Annotaion</i> as <b>input</b> Output : { displayData: `And I should inp ...

What is the best choice for a PHP Session class to use?

I am interested in incorporating session management for user logins, authenticated forms, and pages. Can anyone recommend a reliable wrapper/helper class to simplify this process? If you have created or found a helpful class that you would like to share a ...

Ways to turn off logging for an Angular application using MSAL

I have integrated the Microsoft Authentication Library msal into my Angular application. However, when I deploy the production version of the app, I notice these logs appearing in the console. What is the best way to turn off this logging? https://i.sstat ...

Tips for showcasing JSON data in an HTML table or list

I am seeking a way to dynamically display changing JSON object data in a table using Angular. The structure of the JSON object is subject to change due to server updates. JSON Object: { "This item has 1 value":1, "Another":30, "It ...

What is the process for configuring a TimePicker object in antd to send a Date with UTC+3 applied?

I have Form.Item and a TimePicker defined inside it. I am using this form to send a POST request, but when I try to post 16:35, it gets sent as 13:35. The UTC offset is not being considered. However, the CreationTime works fine because it utilizes the Da ...

Deploying my app on Heroku with two separate folders: a step-by-step guide

I am currently working on a project that involves two separate folders - one for the frontend and another for the back-end. My goal is to deploy both of these folders onto a single Heroku app. Within the server.js file, I have the following code snippet: ...

Urgent dependency alert: calling for a necessity (sequelize) in next.js is a vital element

I'm encountering a challenge with integrating sequelize into my Next.js 13 project to connect my API routes with the database. I keep receiving errors that say "Critical dependency: the request of a dependency is an expression." import * as pg from &a ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value. My objective is to set the initial width value of each div to 0% and then dynamically adjust it t ...

Angular does not support node version 18 or lower

When trying to update my node package, I encountered a warning message. Alert: Angular does not support the current version of Node (18.10.0). If anyone has a solution for this issue, I would greatly appreciate the help. I updated my node using the down ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Why am I unable to apply the keyof operator from one type to another type, even though both types have identical keys defined but different value types?

Consider this code snippet. I am encountering a TypeScript error specifically on the last compat[k] line with the following error message: Type 'keyof T' cannot be used to index type 'Partial<CompatType>' export type KeysOfType ...

Angular2: Retrieve and process a JSON array from an API

I'm currently facing an issue with my service while attempting to fetch a json array from an api and showcase it on the page. I believe there might be an error in my code, but I can't pinpoint exactly where. getAuctions(): Promise<Auction[ ...