Tips on sending a function as a parameter to a TypeScript service

Within my Angular service, I have a method that calls a webapi function:

export class FormulasService extends ServiceBase{
    constructor(){super();}

    renameFormula(id:string, name:string):ng.IPromise<any>{
        var cmd = {id:id, name:name};
        return this.executeCommand('RenameFormula', cmd);
    }
}

Now I have a component that is used in all modules, taking a function as a parameter:

export class RenameModalCtrl extends ControllerBase{
    static $inject=['viewModel']
    constructor(private viewModel:RenameModalModel){
        super();
    }
    saveChanges(){
        this.viewModel.serviceFunction(this.viewModel.id, this.viewModel.name);
    }
}

Accompanied by its model:

export class RenameModalModel{
    constructor(
        public model:any, 
        public serviceMethod:(id:string, name:string)=>ng.IPromise<any>)
}

The corresponding view:

...
<input class="form-control" ng-model="modal.viewModel.model.name" />
<button type="submit" ng-click="modal.saveChanges()">Save Changes</button>
...

The viewModel is resolved during the angular.ui.bootstrap.modal's resolve phase. Utilizing Controller-As syntax, the modal in view represents RenameModalCtrl.

rename()
    {
        var modalInstance = this.$modal.open({
            animation: true,
            controller: 'renameModalCtrl as modal',
            templateUrl: 'renameModal.html',
            resolve: {
                viewModel: new RenameModalModel(this.itemModel, this.formulasService.renameFormula)                    
            }
        });
    }

Although everything works except for the service. Within the service, 'this' refers to the current model instead of the service itself. This causes an issue on the line:

this.executeCommand('RenameFormula', cmd);

How can this be rectified? Your assistance is appreciated

Thank you

Answer №1

To correctly bind class methods to the appropriate "this" reference, it is necessary to utilize the => syntax. The revised version of renameFormula should look like this:

renameFormula = (id: string, name: string): ng.IPromise<any> => {
    var cmd = { id: id, name: name };
    return this.executeCommand('RenameFormula', cmd);
}

For further information on this topic, refer to:

https://example.com/TypeScript/wiki/'this'-in-TypeScript

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

Navigate to AngularJS page utilizing the specified :id value

In my AngularJS Application, I am using ngRoute for routing. While the routing works fine and redirects to the correct page with the right partial open, I am facing an issue in retrieving the necessary item on the second page. The first page allows users ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...

Using Angular's ng-repeat to display a combination of different elements

I'm currently working on transitioning a form from .Net MVC to Angular. I've successfully used ng-repeat to generate the input fields within the form, which is working well. However, I now need to incorporate select fields along with the text inp ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...

ES6 AngularJS 1: The Power of $inject and Inheritance

I am facing a situation where I have 3 child controllers that extend a shared parent controller. The structure looks like this: class ParentController { constructor( $scope, $state ){ this.$scope = $scope; this.$state = $state; } } ...

Video not updating with new source URL

I am currently facing an issue when attempting to assign a source to a video in AngularJS. Below is the HTML code for the view: <div class="row"> <div class="col-lg-10 col-lg-offset-1"> <video width="100%" controls> < ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

I require the ability to modify cellEditor parameters in real-time

How can a value be passed to cellEditorParams after the user double clicks on a grid row? The application triggers a service call on row click and the response needs to be sent to cellEditorParams. ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

I am having trouble getting debugging with source maps to work in VSCode and Browserify

I'm currently experiencing an issue with setting breakpoints in Chrome using VSCode, especially when working with TypeScript and Browserify. Oddly enough, if I open Chrome separately and manually refresh the page, the source maps load correctly and I ...

Guide on Reacting to an Occurrence in Angular

I have a scenario where an event is triggered every 10 seconds. After subscribing to the event on the receiving end, I need to figure out how to send data back to the class responsible for emitting the event. constructor(@Inject(ABC.XYZ) private events: ...

Having trouble injecting $resource into my Jasmine unit test

I've encountered an issue while trying to test my self-written service that utilizes $resource. I'm facing difficulties when trying to inject $resource into my test spec. My setup includes Typescript with AngularJS 1.6.x, and here is a snippet o ...

Navigating the maze of Material UI in React with TypeScript

I have a functioning code, but I am trying to incorporate Material UI into it. However, when I replace 'input' with 'TextField', I encounter the following error: Uncaught (in promise) Error: Request failed with status code 422 at cr ...

Cypress error: Unable to access 'uid' property as it is undefined

Recently in my Cypress project with TypeScript support utilizing the Cucumber Preprocessor, an unexpected exception has started appearing: TypeError: Cannot read properties of undefined (reading 'uid') There are instances where changing to a di ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

The or operator in Typescript does not function properly when used as a generic argument

My current configuration is as follows: const foo = async <T>(a): Promise<T> => { return await a // call server here } type A = { bar: 'bar' } | { baz: 'baz' } foo<A>({ bar: 'bar' }) .then(response =& ...

Angular does not recognize the boolean variable

Within my Angular component, I have declared two boolean variables: editingPercent: boolean = true; editingCap: boolean = false; In the corresponding HTML file, there is a checkbox that updates these variables based on user input: checkedChanged(e) { ...

Unable to update the scope upon $emit in the component

In my AngularJS component, I have a value stored in the scope that provides a URL to an <img> element in the view. Whenever a user changes the image, the controller emits a change using $rootScope.$emit, causing the URL value to update. Ideally, the ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...