是否有正确的方法从 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)工作没有错误,但我不认为(从打字稿/角度改变DOM)是正确的方法。
我找到了这个 :使用 Typescript 中的 Javascript 函数 https://stackoverflow.com/questions/21544893/using-a-javascript-function-from-typescript我尝试声明接口:
interface MYTHEME {
documentOnLoad: Function;
documentOnReady: Function;
}
但 TypeScript 似乎无法识别它(接口声明中没有错误)。
Thanks
Edit :
根据胡安·门德斯的回答,我的结论是:
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();
}
}