In Angular 2, how does the "this" keyword from the subscribe method reference the class?

I am using a subscription for Observable, and when it finishes I need it to call a function from this class. The issue is that the "this" keyword refers to the subscription and not to the class scope. Here is the code snippet:

export class GoogleMapComponent{

    Position: object;

    constructor(public MapFunctionsProvider: MapFunctionsProvider) { 

        let posObservable = this.MapFunctionsProvider.getPosition();

        posObservable.subscribe(data =>{
            this.Position = data;
            this.createMap(); // "this" keyword refers to the subscription
        }); 

        function createMap(){
            console.log('run');
        }
    }
}

How can I call createMap() without declaring a new variable for the "this" keyword?

Answer №1

It is advisable to move the function outside of the constructor because when this is used, it points to the GoogleMapComponent class.

export class GoogleMapComponent {

    Position: object;

    constructor(public MapFunctionsProvider: MapFunctionsProvider) {

        let posObservable = this.MapFunctionsProvider.getPosition();

        posObservable.subscribe(data => {
            this.Position = data;
            this.createMap(); // here 'this' refers to the subscription
        });


    }

createMap(): any {
 console.log('run')
}
}

Answer №2

This has nothing to do with React and is a unique ES7 feature.

Whenever you utilize arrow functions ()=>(), the reference to this. will consistently point back to the original instance of the component regardless of how deeply nested your code may be.

If this behavior is not desired, you still have the option to use regular function(){} declarations.

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

What could be causing the errors I'm encountering in my TypeScript component within AngularJS?

I am working with an AngularJS component written in TypeScript called news.component.ts. This component makes a call to a service named google.service.ts in order to fetch news RSS using a service that converts XML to JSON. Within the NewsComponent, I hav ...

I'm struggling to include a link in my project card component - I've tried using both the Link tag and anchor tag, but so far, I haven't been successful in

I am having trouble getting the link tag to work properly in my UI. I have tried using both the link and anchor tags, but neither seems to be functioning as expected. Can someone please advise on how to fix this issue? https://i.sstatic.net/tAD7C.png I w ...

Sending a pdf file from the Django backend to the Angular frontend

I've tried various solutions for similar issues, but none have worked with my specific case. My goal is to fetch a PDF file from the filesystem using Django and then send it back via an API call to Angular for display. In Django, my code looks like th ...

The Angular template is throwing an error stating that c_r1.getCatType is not a valid function

Within my Angular project (version 9.1.0), I have a class structured like this: export class Contract { contractName: string; limit: number; public getCatType(): string{ if(this.limit > 0) return 'p'; return &ap ...

The close button in Angular 4 is unresponsive until the data finishes loading in the pop-up or table

Having trouble with the Close button in Angular 4 popup/table The Pop Up is not closing after clicking anywhere on the screen. I have added backdrop functionality so that the pop-up closes only when the user clicks on the close icon. However, the close i ...

Dealing with ViewChild and Stepper ExpressionChangedAfterItHasBeenCheckedError in Angular 8

I am currently facing an issue while using ViewChild to access a child component's attribute in the Stepper [completed] property. The problem is related to the "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. ...

What could be the reason for the absence of the Froala editor display

I integrated the Froala editor into my Angular2 project but it doesn't seem to be visible on the screen, and there are no errors present. I made sure to import the necessary modules into app.module.ts, included jQuery in main.ts, and added the scripts ...

At what point does the constructor of an injected service in Angular execute?

When using @Injectable({providedIn: 'root'}) in Angular 7 for a service, the constructor of the service executes when exactly? Is it upon the creation of a component that utilizes it as a dependency or does it wait until a method within the servi ...

What is the best way to display the loan detail and credit detail tables beneath the application detail section that is currently blank?

I have a total of four tables on my page. The size of one table is almost identical to the other three smaller tables. I am looking to place the loan details and credit details table below the application detail, in a way that utilizes the empty space avai ...

Whenever I try to log in on Angular 11, I encounter the HttpErrorResponse error with a status code of

I have encountered an error and cannot seem to find a solution. Here is the code snippet: login(signInRequestPayload: SignInRequestPayload): Observable<boolean> { return this.httpClient.post<SignInResponse>( '/api/v1/registration/login&apo ...

Encountering an issue where the useMutation function is not recognized on the DecorateProcedure<MutationProcedure> type while attempting to utilize the useMutation feature

Currently, I am utilizing the NextJS app router. I am attempting to invoke a rather straightforward route: import { z } from "zod"; import { createTRPCRouter, publicProcedure } from "~/server/api/trpc"; // document sending user email to waitlist da ...

Types for Vue libraries

I am in the process of developing a Vue library as an NPM package with the intention of making it available for use in other projects. The main entry point is main.ts, which exposes a plugin and some commonly used functions. Here's a simplified examp ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

The mat-slide-toggle updates the values for all products, with each value being unique

In my app, I am using Material slide-toggle to control the activation status of products. However, I am facing the following issues: Whenever I toggle one product, it affects the values of all other products as well. The displayed value does not match t ...

Implementing TypeScript inheritance by exporting classes and modules

I've been struggling with TypeScript's inheritance, it seems unable to resolve the class I'm trying to inherit. lib/classes/Message.class.ts ///<reference path='./def/lib.d.ts'/> ///<reference path='./def/node.d.ts& ...

Tips for maintaining the menu state following a refresh

Is there a way to save the menu state when pressing F5? I'm looking for a similar functionality as seen on the Binance website. For example, clicking on the Sell NFT's submenu and then refreshing the page with F5 should maintain the menu state on ...

Error in Reactive Form: Null Property Reading Issue

Issue: Encountered a Cannot read property errors of null error in the form group. I have implemented a reactive form with validation, but I keep running into this specific error. Here is the complete form control setup: <div class="container mt- ...

`Inconsistencies in console.log output with Angular Firestore``

I'm currently working on retrieving the id of selected data, but when I test it using console.log, it keeps outputting twice. The image below illustrates the console.log output. https://i.stack.imgur.com/IARng.png My goal is to fetch the id once and ...

The data type 'number' cannot be assigned to the data type 'undefined'. Error code: ts(2322)

I encountered an issue where it's giving me an error stating that type number cannot be assigned to type undefined on the last digit (1) in scale={[1.618, 1, 1]}. Can anyone help me figure out how to resolve this TypeScript error? "use client&quo ...

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...