0

I am using Third party Library MarvinJS in my Angular5 Application. I need to call a method this.sharedService.openMarvinModal(false); after resolving the MarvinJS promise.

When I invoke the method, it is giving error.

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

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);
      });
    });
  }
}

How can I get around this issue? Any one can please help me.

Thanks in advance.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Krishna
  • 760
  • 3
  • 14
  • 30

1 Answers1

2

You need to replace function with simple arrow function - to not create another context to which this refers.

p.then((sketchInstance) => {
   sketchInstance.exportStructure("smiles").then((source) => {
      console.log(source);
      this.sharedService.openMarvinModal(false);
   });
});
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112