【问题标题】:How to access global js variable in angular2 component如何访问angular2组件中的全局js变量
【发布时间】:2016-10-06 09:04:17
【问题描述】:

我在下面定义了一个全局 js 变量(@Url 是一个 ASP.Net MVC html 帮助器,它将被转换为字符串值):

<script>
  var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)';
  System.import('app').catch(function(err){ console.error(err); });
</script>

如何在 angular2 组件中访问 rootVar?我以前在 angular 1.5 中使用窗口服务,在 angular2 中是否有类似的方法?

具体来说,我想使用那个 rootVar 变量来帮助在这个组件中生成 templateUrl:

import { Component, Inject} from '@angular/core';

@Component({
    selector: 'home-comp',
    templateUrl: '../Home/Root'
})

export class HomeComponent {   
    constructor( ) {  }
}

【问题讨论】:

标签: typescript angular


【解决方案1】:

您需要更新引导应用程序的文件以导出函数:

import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';

export function main(rootVar) {
  bootstrap(AppComponent, [
    provide('rootVar', { useValue: rootVar })
  ]);
}

现在您可以通过这种方式从index.html 文件中提供变量:

<script>
  var rootVar = '@Url.Action("Index","Home",new { Area = ""}, null)';
  System.import('app/main').then((module) => {
    module.main(rootVar);
  });
</script>

然后您可以通过这种方式将rootVar 注入到组件和服务中:

import { Component, Inject} from '@angular/core';

@Component({
  selector: 'home-comp',
  templateUrl: '../Home/Root'
})
export class HomeComponent {   
  constructor(@Inject('rootVar') rootVar:string ) {  }
}

【讨论】:

  • 谢谢,我可以按照您的示例访问组件中的变量,但遇到了新问题。现在我已经将 rootVar 注入到构造函数中,我似乎无法使用它来修改组件 templateUrl。 @Component({ selector: 'home-comp', templateUrl: '..{{baseUrl}}Home/Root' }) 导出类 HomeComponent { baseUrl: string;构造函数(@Inject('rootVar') rootVar: string) { this.baseUrl = rootVar; } }
  • 不客气!实际上,您不能以这种方式使用变量来构建 tempalteUrl 路径。一个是在类级别和其他实例级别...在您的情况下,我会尝试扩展 UrlResolver 类并将您的变量注入其中。请参阅此链接:angular.io/docs/ts/latest/api/compiler/UrlResolver-class.html
【解决方案2】:

另一种方法是导出您的 var,例如:

  export var API_ENDPOINT = '@Url.Action("Index","Home",new { Area = ""}, null)';

然后在你的组件中导入它

import {API_ENDPOINT }

【讨论】:

    【解决方案3】:

    在您的组件中,您可以引用 window 来访问全局变量,如下所示:

    rootVar = window["rootVar"];
    

    let rootVar = window["rootVar"];
    

    【讨论】:

      【解决方案4】:

      在组件文件中,在组件类定义之外,声明rootVar,它将在组件构造函数中变为可用:

      declare var rootVar: any;
      

      然后

      @Component(...)
      export class MyComponent {
        private a: any;
      
        constructor() {
          this.a = rootVar;
        }
      }
      

      【讨论】:

      • 重要的注意事项。我无法让组件类外部的声明对组件类中的任何方法可见。您需要在构造函数中设置一个实例变量来引用全局变量,然后在您的方法中引用该变量
      【解决方案5】:

      这里别忘了洗手……Angular 只是 javascript

      //Get something from global
      let someStuffFromWindow= (<any>window).somethingOnWindow;
      
      //Set something
      (<any>window).somethingOnWindow="Stuff From Angular";
      

      由于某种原因这很糟糕..你应该感到难过!

      继续使用 window. 的查找和替换函数为 (&lt;any&gt;window).

      【讨论】:

      • window['somethingOnWindow'] 看起来更干净。不要问我为什么
      • 为什么? @redent84 (sorry couldn't help it)
      • 我认为一般[] 用于动态字段。使用 property.value 用于非动态字段(请参阅 airbnb 样式指南)。
      • 谢谢。找了很久才找到没有5个文件40行代码的解决方案。
      • 我更喜欢类型转换,所以它看起来有点复杂,以适应其余的代码,我可以假装我是聪明的 Typescript
      【解决方案6】:

      在 HTML 模板中你可以使用 get 方法

      <span>{{getGlobalData('rootVar')}}</span>
      

      并在组件中创建方法,如:

      get getGlobalData() {
          // Closure workaround
          return function(rootVarName) {
              return window[rootVarName];
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-06-15
        • 2016-07-16
        • 2017-12-16
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多