是否存在从Angular 2(TypeScript)中的组件调用JavaScript函数的正确方法?
这是我的组件:
import { ElementRef, AfterViewInit } from '@angular/core';
export class AppComponent implements AfterViewInit {
constructor(private _elementRef: ElementRef) {
}
ngAfterViewInit() {
/**
* Works but i have this error :
* src/app.component.ts(68,9): error TS2304: Cannot find name 'MYTHEME'.
* src/app.component.ts(69,9): error TS2304: Cannot find name 'MYTHEME'.
*/
MYTHEME.documentOnLoad.init();
MYTHEME.documentOnReady.init();
/**
* Works without error, but doesn't seem like a right way to do it
*/
var s = document.createElement("script");
s.text = "MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init();";
this._elementRef.nativeElement.appendChild(s);
}
}
直接调用JavaScript函数会导致编译错误,但是“已编译” JavaScript文件(app.component.js)中的语法正确:
AppComponent.prototype.ngAfterViewInit = function () {
MYTHEME.documentOnLoad.init();
MYTHEME.documentOnReady.init();
};
第二种方法(appendChild)没有错误,但是我不认为(更改Typescript / angular中的DOM)是正确的方法。
我发现了这一点:使用来自Typescript的Javascript函数,我尝试声明了接口:
interface MYTHEME {
documentOnLoad: Function;
documentOnReady: Function;
}
但是TypeScript似乎无法识别它(接口声明中没有错误)。
谢谢
编辑 :
按照胡安·门德斯的回答,这就是我的结尾:
import { AfterViewInit } from '@angular/core';
interface MYTHEME {
documentOnLoad: INIT;
documentOnReady: INIT;
}
interface INIT {
init: Function;
}
declare var MYTHEME: MYTHEME;
export class AppComponent implements AfterViewInit {
constructor() {
}
ngAfterViewInit() {
MYTHEME.documentOnLoad.init();
MYTHEME.documentOnReady.init();
}
}
您必须使用告诉TypeScript有关外部(JavaScript)声明的信息declare
。参见https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html
interface MyTheme {
documentOnLoad: Function;
documentOnReady: Function;
}
declare var MYTHEME: MyTheme;
或匿名
declare var MYTHEME: {documentOnLoad: Function, documentOnReady: Function};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句