Angular 2 typescript调用javascript函数
发布时间:2020-12-17 07:26:28 所属栏目:安全 来源:网络整理
导读:是否有正确的方法从Angular 2(TypeScript)中的组件调用 JavaScript函数? 这是我的组件: import { ElementRef,AfterViewInit } from '@angular/core';export class AppComponent implements AfterViewInit { constructor(private _elementRef: ElementRef)
是否有正确的方法从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)是正确的方法. 我发现了这个:Using a Javascript Function from Typescript我尝试声明界面: 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}; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angularjs – 似乎无法获得’karma-ng-html2js-preprocesso
- Kubernetes - - k8s - v1.12.3 Helm持久化部署 Redmine 集成
- Angular企业级开发(7)-MVC之控制器
- shell – 终端:CURL |走到JsonPath | prettyprint JSON
- 如何在Unix/Linux中获取进程的路径
- 在scala中匹配case类:?(a,b)匹配{case a~b => …}
- AngularJS – 如何覆盖指令ngClick
- 在scala宏中推断一种树的类型
- vim-surround不适合我的钥匙删除而不是围绕
- 在scala中实施长时间的投票,并与akka一起玩2.0