如何在解析jQuery promise后调用angular2方法[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我在Angular5应用程序中使用第三方库MarvinJS。在解决了MarvinJS的承诺后,我需要调用一个方法this.sharedService.openMarvinModal(false);

当我调用该方法时,它给出了错误。

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

代码片段:

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

我该如何解决这个问题?任何人都可以请帮助我。

提前致谢。

angular typescript
1个回答
2
投票

你需要用简单的function替换arrow function - 不要创建this所指的另一个上下文。

p.then((sketchInstance) => {
   sketchInstance.exportStructure("smiles").then((source) => {
      console.log(source);
      this.sharedService.openMarvinModal(false);
   });
});
© www.soinside.com 2019 - 2024. All rights reserved.