在打字稿中使用组件类属性进行外部JS文件回调

时间:2019-07-12 08:11:06

标签: javascript angular typescript object

我正在像这样在我的角度组件中使用外部js文件:

declare var external: any;

@Component({
  selector: 'payment-form',
  templateUrl: './payment-form.component.html'
})
export class PaymentFormComponent implements AfterViewInit {

  testVar = 'test';

  constructor() {
  }

  ngAfterViewInit(): void {
    external.init({
      'error-callback': this.onExternalError,
      'debug': true
    });
  }
  onExternalError(errors) {
    console.error(errors);
    console.log(this.testVar);
    this.showErrors();
  }

  showErrors() {
    console.log('errors');
  }
}

外部js文件具有一个名为init()的函数,我在ngAfterViewInit()中对其进行了调用。此函数采用回调函数来处理错误,我将其赋予函数onExternalError。它确实在错误时运行正确的功能,我可以看到console.log(errors)。当我尝试使用组件属性中的testVar时,问题将出现在下一行。它无法访问它,也找不到它,因为它可能是使用了不存在testVar的错误实例。

this.showErrors也将不起作用,并且出现错误showErrors() is not a function。关于如何解决此问题的任何想法还是不可能?

2 个答案:

答案 0 :(得分:0)

尝试获取当前上下文并使用它来调用变量:

that = this;
onExternalError(errors) {
    console.error(errors);
    console.log(that.testVar);
    this.showErrors();
  }

答案 1 :(得分:0)

通过使用() => {}而不是函数回调并使用_this = this进行了修复:

declare var external: any;

@Component({
  selector: 'payment-form',
  templateUrl: './payment-form.component.html'
})
export class PaymentFormComponent implements AfterViewInit {

  testVar = 'test';
  external = external;

  constructor() {
  }

  ngAfterViewInit(): void {
    const _this = this;
    this.external.init({
      'error-callback': (errors) => {
        console.error(errors);
        console.log(_this.testVar);
        _this.showErrors();
      },
      'debug': true
    });
  }
}
相关问题