When the promise is resolved, the members of the AngularJS controller are now

I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this:

this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) =>
{
    this.StockItems = StockItems;
    this.CreditNoteStockItems = new Array<ViewModels.CreditNoteStockItemViewModel>();
}

Despite having all members defined in the controller before calling this service method, once the promise is resolved, both this.StockItems and this.CreditNoteStockItems become undefined. Additionally, the assignment of StockItems doesn't seem to reflect in the view. I suspect this might be due to a scope issue where the promise is returning into a new scope. This strange behavior has occurred with other methods as well, seemingly at random.

Could someone shed some light on why this is happening and, more importantly, suggest ways to prevent it from happening again?

Note: The provided code snippet is a simplified version of my controller (excluding additional members and methods).

Additional information about the method in the controller:

export class CreditNoteController
{
    static $inject = ['$scope', '$modalInstance', 'StockService'];

    StockService: Services.StockService;
    ModalInstance: ng.ui.bootstrap.IModalServiceInstance;

    constructor($scope, $modalInstance, StockService: Services.StockService)
    {
        $scope.vm = this;

        this.ModalInstance = $modalInstance;
        this.StockService = StockService;
    }

    InvoicesSelectionChanged()
    { 
        this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) =>
        {
            this.StockItems = StockItems;               
            this.CreditNoteStockItems = new Array<ViewModels.CreditNoteStockItemViewModel>();              

        });            
    }
}

The controller is injected through the angular UI modal service open method located in another controller:

this.ModalService.open(
{
    templateUrl: URL,
    controller: Controllers.CreditNoteController,
});  

Some additional insight on the generated JavaScript:

CreditNoteModalController.prototype.InvoicesSelectionChanged = function () {
    var _this = this;                      

    this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success(function (StockItems) {
             _this.StockItems = StockItems;                        
             _this.CreditNoteStockItems = new Array();                       
         });
};

Any help or guidance would be greatly appreciated. Thank you!

Answer №1

Through some discussion in the comments, it became apparent that there were actually two separate issues at play here, so I have summarized the information into the answer:

  1. When examining 'this' in a debugger within a .ts file, keep in mind that you will be viewing the actual 'this' value and not the _this alias that is generated in the .js file when using arrow functions. This discrepancy can sometimes give the appearance of variables not being properly set, when in fact you are looking at the incorrect variable. Adding a watch on _this will display the correct one. Alternatively, you can also utilize console.log on 'this' directly in the TypeScript code, as it will compile to use the _this alias.

  2. It was discovered that ng-options requires ng-model in order to function correctly.

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

Steps for managing files in Ionic Native: creating, reading, and writing them

Struggling to find proper examples for file operations like creating, reading, and writing text or logs into a file? I've done a lot of research but haven't stumbled upon any suitable solutions. The examples provided in this link seem helpful, ho ...

Issue: The value of an object is not defined (evaluating '$scope.inputcode.password')

HTML Form: <form ng-submit="mylogin()"> <div class="list"> <label class="item item-input"> <span class="input-label">Username</span> <input type="text" ng-model="inputcode.username"> ...

Ionic 2 encountering issue with `ctorParameters.map` not being a function error

Recently, I wanted to incorporate the Network-information plugin into my project but encountered compatibility issues with an older version of Ionic-native. To resolve this, I took the following steps: npm rm --save ionic native npm install --save ionic-n ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Is it possible to export an imported merged namespace in Typescript?

Within my library, I have a collection of merged declarations setup like this: export class Foo {...} export namespace Foo { export class Bar {...} ... } export default Foo These merged declarations often contain inner classes and specific errors r ...

Attempting to execute JavaScript within HTML files that have been incorporated using Angular

My website has a menu designed in HTML, and instead of manually adding it to each page (which would make updating changes tedious), I am using Angular to include it dynamically (<div ng-include="menu.html"></div>). I've got some JavaScrip ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

Struggling to Decode Octet-stream Data in Angular 6 HttpClient: Encountering Parsing Failure with Error Prompt: "Failed to parse HTTP response for..."

Is there a way to make a non-JSON request to the server using Angular 6 HttpClient (@angular/common/http) in order to receive an Octet-stream? Below is the code I have tried: getFile(file: any) { let headers = new HttpHeaders({ 'Content-T ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

In Typescript, an interface is defined where the "id" property is required to be a number, while all other properties must be of

I am in need of creating an interface to represent data received from the server, where the id is a number and all other properties are strings. This is what I attempted: interface AnyChartsData { id: number; [key: string]: string; } However, I enco ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

Is it possible to use npm to create an AngularJS project?

Is it possible to create an AngularJS project structure using npm or any other commands? Just like we use the following command to create a new angular project: ng new application_name Similarly, for creating a new react app we use: npx create-react-app ...

Navigating to various views using both forward and back buttons in AngularJS

In the index.html file, there is a footer with next and previous buttons. The code structure looks like this: <html ng-app="myapp"> <body ng-controller="myController"> <div id="header">Header</div> <div id="content"><ng-vi ...

Is it possible to define an interface to inherit keys from another interface?

I have two different interfaces that I need to align their key structure, but not necessarily the values they hold. One interface (Thing) is sourced from an external library, while the other interface (ThingOptions) is defined in my own project. interface ...

Determining if a method's timeout has been triggered while running on a periodic basis in JavaScript

Within my JavaScript code, I have implemented a method that runs every 5 minutes. However, after 15 minutes, I want to stop this method from executing. var tChk ; tChk = setInterval("test()", 5*60*1000); setTimeout("timeOut(tChk)", 15*60*1000); // 15 mins ...

Prevent altering client values via developer tools

Our application is built using HTML5, the Foundation framework by ZURB, and AngularJS. We are seeking a way to prevent users from accessing and changing the values of our Angular objects (specifically scope variables) through the developer tool console. ...

The ActivatedRoute snapshot does not function properly when used in the TypeScript class constructor

Currently, I am encountering a challenge with TypeScript and Angular 2. The structure of my TS class is as follows: 'import { Component, OnInit } from '@angular/core'; import {ActivatedRoute} from '@angular/router'; @Component({ ...

Saving an array object to a file in JSON formatting

In the midst of my work on an Angular project, I have successfully compiled data into an array and am able to download it as a CSV file using an Angular package. However, I have not been able to locate a suitable package that allows me to download the sa ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...