RxJS: Understanding the issue of 'this' being undefined when used within the subscribe method

As I work on setting up a simple error notifications component and debug in Visual Studio, an issue arises within the subscribe function where 'this' is undefined.

public notifications: NotificationMessage[]; 

constructor(notificationService: NotificationService) {
    this.notifications = []; //'this' is defined here

    notificationService.rxEmitter.subscribe((notificationMessages: any) => {
        this.notifications = notificationMessages; //'this' is undefined here
    });
}

Update : Here is a screenshot showing 'this' being undefined at a breakpoint in VS. Interestingly, '_this', despite existing at runtime, cannot be referenced as TypeScript throws a reference not found error during compilation.

Answer №1

After some investigation, I realized that the Visual Studios debugger was misleading me by indicating that something was undefined. However, when I tested it with console.log, I received a valid output.

It appears that Visual Studio struggles with arrow functions, as Typescript compiles this to _this.

https://i.sstatic.net/1t4nC.png

If you set a breakpoint within subscribe and examine this, Visual Studios debugger will actually be examining the anonymous function in the generated javascript code above and won't be able to find this anymore.

A workaround is to inspect _this instead.

This resource seems to address the issue I encountered.

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

Ordering numbers in Angular2 using a custom pipe

In my Angular2 project, I am attempting to organize an array of strings based on numerical values using a custom pipe that was not authored by me. The code for the pipe is provided below: import { Pipe, PipeTransform } from "@angular/core"; @Pipe( { name ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...

When using Validators.pattern('^[0-9][0-9][0-9]$') in Angular 9, it does not validate numbers with a leading 0, such as 012

When attempting to validate a simple PIN with the possibility of leading zeros, I created this basic regular expression: ^[0-9][0-9][0-9][0-9][0-9][0-9]$ Although this regex worked fine on various online tools for testing regular expressions, it failed i ...

The return value depends on the type of function argument passed

I am currently developing a type-safe JSON:API specification parser for handling API responses that can either contain a single object or an array of objects (). For example, when making a request like GET /article: { data: { type: 'article&ap ...

No data appearing in the console after sending a POST request using Node.js

Is anyone else experiencing issues with retrieving data in the post request below? I'm open to suggestions. var bodyParser = require('body-parser'); var jsonParser = bodyParser.json(); var urlEncodedParser = bodyParser.urlencoded({extende ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

Encountering a TypeScript error while trying to pass the myDecorator function as a decorate prop to React

Encountering a TS error that states: (property) decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined Type '([node, path]: [node: any, path: any]) => { anchor: { path: any; offset: string | number; }; focus: { path: any; offset: ...

Incorporating dynamic dependency injection in Angular 2 through the use of @Input()

Let's consider a scenario where an Angular 2 component-directive needs to dynamically determine the injected dependency it uses based on an @Input(). For example, I would like to be able to specify <trendy-directive use="'serviceA'"> ...

Angular CLI build/serve/test commands task problem matcher in VS Code

In an attempt to set up VS code tasks for Angular CLI commands such as 'ng build', 'ng serve', and 'ng test', I want to generate a list of problems that can be easily navigated when running a CLI command. Currently, I execute ...

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

Unable to locate a compatible version for caniuse-lite with the specified range of ^1.0.30001349

I encountered an error while running npm install: npm ERR! code ETARGET npm ERR! notarget No matching version found for caniuse-lite@^1.0.30001349. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a package v ...

Comparing two inherited classes in Typescript: A step-by-step guide

Let's say we have two classes: Animal and Dog. The Dog class is a subclass of the Animal class. I am trying to determine the types of these objects. How can I accomplish this task? class Animal {} class Dog extends Animal {} //The object can be of ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

Transforming Post Requests into Options Requests

I am facing an issue with my Angular 6 API. After creating interceptors, my POST requests are turning into OPTIONS requests. What could be causing this problem? Here is the code for one of the Services: import { Injectable } from '@angular/core&apo ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Displaying exclusively the country code in an Angular material-select component

This is the HTML code I am using: <mat-form-field style="width: 70px;margin-left: 50px;"> <mat-label>Select an option</mat-label> <mat-select (openedChange)="toogleCountry()" [(value)]="selected"> <mat-option value="+91" ...

Tips for merging arrays conditionally in JavaScript

Currently facing a dilemma without a clear solution, aiming to provide minimal context and focus solely on the problem at hand A worker logs their daily hours at work, stored in the "dayli_data" array. If the worker misses logging hours, it triggers the " ...

Activate the mat-select selectionChange trigger when making changes to the form via patchValue

I have been working with an angular reactive form that includes a mat-select element with a selectionChange event. After updating the form using patchValue, I noticed that the selectionChange event does not trigger. I'm unsure how to proceed and woul ...

Dealing with AOT challenges when integrating ng2-bootstrap into Angular 2 applications

I'm currently developing an Angular 2 app and encountering an error when attempting to create a bundle with AOT compilation following the guidelines in Angular 2 documentation here. The dependency error I'm facing is as follows: Refer to this ...