Angular 2 typescript调用javascript函数

前端之家收集整理的这篇文章主要介绍了Angular 2 typescript调用javascript函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有正确的方法从Angular 2(TypeScript)中的组件调用 JavaScript函数

这是我的组件:

  1. import { ElementRef,AfterViewInit } from '@angular/core';
  2.  
  3. export class AppComponent implements AfterViewInit {
  4.  
  5. constructor(private _elementRef: ElementRef) {
  6. }
  7.  
  8. ngAfterViewInit() {
  9. /**
  10. * Works but i have this error :
  11. * src/app.component.ts(68,9): error TS2304: Cannot find name 'MYTHEME'.
  12. * src/app.component.ts(69,9): error TS2304: Cannot find name 'MYTHEME'.
  13. */
  14. MYTHEME.documentOnLoad.init();
  15. MYTHEME.documentOnReady.init();
  16.  
  17. /**
  18. * Works without error,but doesn't seem like a right way to do it
  19. */
  20. var s = document.createElement("script");
  21. s.text = "MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init();";
  22. this._elementRef.nativeElement.appendChild(s);
  23. }
  24. }

直接调用JavaScript函数会导致编译错误,但“已编译”的JavaScript文件(app.component.js)中的语法是正确的:

  1. AppComponent.prototype.ngAfterViewInit = function () {
  2. MYTHEME.documentOnLoad.init();
  3. MYTHEME.documentOnReady.init();
  4. };

第二种方式(appendChild)工作没有错误,但我不认为(从typescript / angular更改DOM)是正确的方法.

我发现了这个:Using a Javascript Function from Typescript我尝试声明界面:

  1. interface MYTHEME {
  2. documentOnLoad: Function;
  3. documentOnReady: Function;
  4. }

但是TypeScript似乎没有识别它(接口声明中没有错误).

谢谢

编辑:

在Juan Mendes的回答之后,这就是我的结局:

  1. import { AfterViewInit } from '@angular/core';
  2.  
  3. interface MYTHEME {
  4. documentOnLoad: INIT;
  5. documentOnReady: INIT;
  6. }
  7. interface INIT {
  8. init: Function;
  9. }
  10. declare var MYTHEME: MYTHEME;
  11.  
  12. export class AppComponent implements AfterViewInit {
  13.  
  14. constructor() {
  15. }
  16.  
  17. ngAfterViewInit() {
  18. MYTHEME.documentOnLoad.init();
  19. MYTHEME.documentOnReady.init();
  20. }
  21. }
您必须使用declare告诉TypeScript有关外部(JavaScript)声明的信息.见 https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html
  1. interface MyTheme {
  2. documentOnLoad: Function;
  3. documentOnReady: Function;
  4. }
  5. declare var MYTHEME: MyTheme;

或者匿名

  1. declare var MYTHEME: {documentOnLoad: Function,documentOnReady: Function};

猜你在找的Angularjs相关文章