Problem with Anular5 - "this" not functioning correctly inside of ready()

I am encountering an issue in graph.component.ts

this.cContainer = cytoscape ( {  
    ready: function(e) { 
      this._dataService.setResultData();
    }
  });

However, I am getting the following error message:

ERROR TypeError: Cannot read property 'setResultData' of undefined

It appears that this is unrecognized, which makes sense since I am within a callback and this refers to the ready-callback.

How can I properly call _dataService.setResultData() from inside this ready()-callback?

Answer №1

To retain the value of this from the declaring context, you can utilize an arrow function. Using a regular function, the value of this is determined by the caller and may not necessarily refer to your class:

this.cContainer = cytoscape ( {  
    ready: (e) => { 
      this._dataService.setResultData();
    }
  });

Answer №2

When it comes to this, there is a distinction between regular functions and fat-arrow ES6 functions. The latter preserves the context of this. Therefore, instead of using the current function, you can opt for:

ready: e => this._dataService.setResultData();

An alternative approach could be:


ready: function(e) {
   this._dataService.setResultData();
}.bind(this)

However, the second option may not be aesthetically pleasing...

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

Struggling to chart out the post response in Angular 7

I am facing an issue while setting up a service on Angular version 7. The problem arises with the res.json() method, throwing an error stating Property 'json' does not exist on type 'Object'. Below is my service's code: import {In ...

Ways to sort through a Unix timestamp

Recently, I encountered an issue with my Ionic mobile application. It has a search button and filter feature that works well for filtering words. However, the problem arises when it comes to filtering dates displayed in the app as timestamps using Angular ...

Struggling to create a functioning toggle button using jQuery in a React application

I've encountered an issue with my react web application. I'm trying to implement a voting system where clicking the like button changes its color and functionality, allowing it to be liked only once. If clicked again, it should return to a neutra ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

Experience the magic of changing backgrounds with Ionic 4's dynamic image feature

I am currently facing an issue while attempting to add multiple background images in my Ionic 4 project. I have successfully created styles for static images, but when it comes to dynamic images, I encounter errors with the styles. <ion-content st ...

Make the if statement easier - Angular

Would you like to know a more efficient way to streamline this If statement? The variables are all strings and are reused in both conditions, but the outcome varies depending on whether it returns true or false. if(params.province && !params.str ...

Setting up configurations in an Angular app using environment variables from a Spinnaker manifest

In the spinnaker manifest, I have certain Environment-specific variables stored that I need to replace in my Angular app when it's deployed to different environments such as dev, qa, and prod. How can I modify my code to accomplish this? The reason be ...

Eliminate all citation markers in the final compiled result

Currently, I am consolidating all my .ts files into a single file using the following command: tsc -out app.js app.ts --removeComments This is based on the instructions provided in the npm documentation. However, even after compilation, all reference tag ...

I'm curious as to why my array is only being filled within the subscription function

When I call the GetAllMainStore() function, data is successfully retrieved from the API and the console indicates that "this.MainStoreArray" contains data. The problem arises when I attempt to access "this.MainStoreArray" outside of the GetAllMainStore() ...

Reading text files line by line in TypeScript using Angular framework is a valuable skill to have

Struggling with reading text files line by line? While console.log(file) may work, it doesn't allow for processing each individual line. Here's my approach: In api.service.ts, I've implemented a function to fetch the file from the server: ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

"Looking to personalize marker clusters using ngx-leaflet.markercluster? Let's explore some ways to customize

I am currently struggling to implement custom cluster options in ngx-leaflet. My goal is simply to change all marker clusters to display the word "hello". The demo available at https://github.com/Asymmetrik/ngx-leaflet-markercluster/tree/master/src/demo/a ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

Encountering issues with integrating the node_module (website scraper) in Angular 4 for implementation

Recently, I've been attempting to integrate the node_module "website scraper" [1] into my Angular 4 project. After downloading and installing the module using "npm install website-scraper –save", I proceeded to import it in my Component with "import ...

Can an Observable be created that emits an array produced by awaiting asynchronous methods?

I've encountered an issue with the following method: get fileResults$(): Observable<File[]> { return this.ngRedux.select<ICommunicationState>('communication').pipe(map(newState => { const files: File[] = []; ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

ways to display selected custom information with a choiceLabel in a dropdown using primeng

Is there a way to display custom data on a dropdown in Primeng while also showing the selected data as shown in the dropdown list? Please refer to both images below for clarification. <div class="p-grid" *ngIf="deleteUser" style=&quo ...