在HTML文件中使用System.js调用打字稿类方法



我正在尝试打开打字稿和system.js。打字稿编译器正在使用-W标志运行。

我想在页面加载时调用一种方法,我可以导入播放,但不能用"然后"访问它:

html文件:

<!doctype html>
<head>
  <script src='//cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.41/system.js'> </script>
  <script>
    System.import('./play.js').then(function(play) { 
      play.start(); 
    });
  }
  </script>
</head>
<body>
</body>

play.ts文件:

export class Play {
  start() {
    alert('hello...');
  }
}

我得到错误: Uncaught (in promise) TypeError: play.start is not a function。有什么想法吗?

System.import结果是一个模块,而不是类。返回的模块具有从中导出的所有内容的引用,因此您可以将Play类作为play.Play,但是要调用start()方法,您必须使用new首先创建该类的对象。这样的事情应该有效:

  <script>
    System.import('./play.js').then(function(play) { 
      var player = new play.Play();
      player.start(); 
    });
  }
  </script>

最新更新