首页 > 解决方案 > 从 typescript 调用使用 c# 注册的 javascript 函数

问题描述

我使用 RegisterStartupScript 从 C# 添加了一个函数调用,如下所示:

Page.ClientScript.RegisterStartupScript(this.GetType(), "PrintWindowJScript", "<script type=\"text/javascript\">OpenNewWindow() { Reports_OpenWindowNamed(URL, 350, 250, \"PrintAttachPopupWindow\"); }</script>");

上面的代码会将它添加到 DOM 中,所以当我调用 OpenNewWindow() 时,它应该从我的 Angular 组件中调用该函数。

现在在我的角度组件中,我在 Typescript (Angular) 中有一个下拉更改功能。我需要从这里调用 OpenNewWindow(),如下所述。

interface IMyWindow {
  OpenNewWindow: Function;
}
declare var v_MyWindow: IMyWindow ;

export class MyComponent implements OnInit {

  ngOnInit() {
  }

  attachChange(attachDropDown: any) {
    if(attachDropDown.value && attachDropDown.value.id == "MyValue"){
      v_MyWindow.OpenNewWindow();
    }
  }
}

上面的代码给了我未定义的“v_MyWindow”。

我试过参考这篇文章,但没有用。

如果我遗漏了什么,谁能告诉我?我应该怎么做才能调用该函数?

标签: javascriptc#angulartypescript

解决方案


您已经创建了接口并声明了变量v_MyWindow,您只需要分配属性OpenNewWindow

改变:

Page.ClientScript.RegisterStartupScript(this.GetType(), "PrintWindowJScript", "<script type=\"text/javascript\">OpenNewWindow() { Reports_OpenWindowNamed(URL, 350, 250, \"PrintAttachPopupWindow\"); }</script>");

到:

Page.ClientScript.RegisterStartupScript(this.GetType(), "PrintWindowJScript", "<script type=\"text/javascript\">v_MyWindow.OpenNewWindow = function() { Reports_OpenWindowNamed(URL, 350, 250, \"PrintAttachPopupWindow\"); }</script>");

推荐阅读