Tips on triggering an Angular 2 method once a jQuery promise has been resolved

I am currently incorporating the Third Party Library called MarvinJS into my Angular5 Application. In order to successfully handle a MarvinJS promise, I need to execute the method

this.sharedService.openMarvinModal(false);
.

However, upon executing this method, an error occurs.

Uncaught (in promise) TypeError: Cannot read property 'sharedService' of undefined
at eval (marvin-modal.component.ts:58)
at <anonymous>

Here is the relevant code snippet:

import {
  Component,
  OnInit
} from "@angular/core";

import { SharedService } from "../services/shared.service";

import * as $ from "jquery";
declare var MarvinJSUtil: any;

@Component({
  selector: "app-marvin-modal",
  templateUrl: "./marvin-modal.component.html",
  styleUrls: ["./marvin-modal.component.scss"]
})
export class MarvinModalComponent
  implements OnInit {

  constructor(private sharedService: SharedService) {}

  ngOnInit() {
  }

  getStructure() {
    const p  = MarvinJSUtil.getEditor("#sketch");
    p.then(function(sketchInstance) {
      sketchInstance.exportStructure("smiles").then(function( source) {
        console.log(source);
        this.sharedService.openMarvinModal(false);
      });
    });
  }
}

I am seeking assistance on how to resolve this issue. Any help would be greatly appreciated.

Thank you in advance.

Answer №1

In order to avoid creating another context that this refers to, you should replace the function with a straightforward arrow function.

p.then((sketchInstance) => {
   sketchInstance.exportStructure("smiles").then((source) => {
      console.log(source);
      this.sharedService.openMarvinModal(false);
   });
});

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

Having trouble retrieving information from a controller action in .NET Core and Angular 2

My Angular 2 service: private checkEmailAvailabilityUrl = 'api/admin/checkemailavailability'; checkEmailAvailability(email: string): Observable<boolean> { let params = new URLSearchParams(); params.set('email', email); ...

Discovering JSON data in Angular 4

I am working with a JSON data format retrieved from (this.url) { "user": [ { "id": "1", "name": "root", "password": "root" }, { "id": "2", "name": "clienttest", ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...

Embedding a table row within an anchor element in Angular 4

Currently, I am facing an issue with a table that contains [routerLink] on each <tr>. This setup is preventing the "open link in a new tab" option from appearing when I right-click because there is no <a> tag. I attempted to enclose the table r ...

Set the boolean input property by checking for the existence of an attribute on the directive

Is it possible to set an input property for a directive by simply including it without passing a value? <my-component [customInput]='true'></my-component> However, with boolean input properties, I am having trouble figuring out how ...

Using a mock with ts-jest shows an error stating that property 'mockImplementation' does not exist on type

I'm facing an issue with my code as I attempt to run a Jest test using ts-jest. jest.mock('../foo'); import configure from '../configure'; import foo from '../foo'; test('test name', () => { foo.mockImplem ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

After applying the withStyles and withTranslation higher order components to a React component, a Typescript error is displayed

Trying to create a React component using Typescript, incorporating withStyles from @material-ui/core and withTranslation from react-i18next, both of which are Higher Order Components (HOC). Encountering a typescript error when using them together. Specif ...

Modify the animation attribute of the <circle> element using AngularJS

A new feature I implemented in my web app is a customizable countdown timer. As an added visual enhancement, I am now looking to create an animated circle around the timer. The animation duration will vary based on the countdown length. Here is a snippet ...

Forbidden access to Angular 4 web application on S3 following redirection

Recently, I developed a basic angular 4 application that utilizes firebase for authentication. Due to issues with loginWithPopup on my mobile device, I switched to using loginWithRedirect. However, the problem arises when the redirect takes me away from t ...

Using vue-router within a pinia store: a step-by-step guide

I'm currently setting up an authentication store using Firebase, and I want to direct users to the login/logged page based on their authentication status. My goal is similar to this implementation: https://github.com/dannyconnell/vue-composition-api- ...

What is the best way to extract values from a TypeORM property decorator?

import { PrimaryColumn, Column } from 'typeorm'; export class LocationStatus { @PrimaryColumn({ name: 'location_id' }) locationId: string; @Column({ name: 'area_code', type: 'int' }) areaCode: number; } I& ...

Sticky-top Navbar in Angular5 and Bootstrap4

The "sticky-top" Bootstrap navbar position only functions if the navbar is a direct child of: <body> <header class="sticky-top"> <nav class="navbar navbar-light bg-light p-0"> ... </nav> </header> </bod ...

The React component using createPortal and having its state managed by its parent will remain static and not refresh upon state modifications

I am facing a problem that can be seen in this live example: https://stackblitz.com/edit/stackblitz-starters-qcvjsz?file=src%2FApp.tsx The issue arises when I pass a list of options to a radio button list, along with the state and setter to a child compon ...

An error has occurred in the tipo-struttura component file in an Angular application connected with a Spring backend and SQL database. The error message indicates that there is a TypeError where the

Working on my project that combines Spring, Angular, and MYSQL, I encountered a challenge of managing three interconnected lists. The third list depends on the second one, which in turn relies on user choices made from the first list. While attempting to l ...

Trouble encountered while configuring and executing Electron combined with React, Typescript, and Webpack application

I am currently in the process of migrating my Electron application from ES6 to Typescript. Despite successfully building the dll and main configurations, I encounter a SyntaxError (Unexpected token ...) when attempting to run the application. The project c ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

Retrieve the unchanged data from the source before any modifications using ag-Grid

Is the original data saved anywhere when accessing data with the ag-Grid API? For instance, can it be retrieved from: api.getRowNode(id) This information could come in handy, especially if you want to highlight an edited cell by comparing values and chan ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

Visual Verification

I'm currently working on a NestJS application that serves images with authentication requirements. I have implemented JWT for authentication, but I encountered an issue when trying to display the image in an img tag because I cannot attach the Authori ...