[英]Angular 2 typescript invoke javascript function
是否有正確的方法從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似乎沒有識別它(接口聲明中沒有錯誤)。
謝謝
編輯:
在Juan Mendes的回答之后,這就是我的結局:
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();
}
}
您必須使用declare
告訴TypeScript有關外部(JavaScript)聲明的信息。 請參閱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};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.