如何在angular2组件中访问全局js变量 [英] How to access global js variable in angular2 component

查看:99
本文介绍了如何在angular2组件中访问全局js变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a global js variable defined below (@Url is an ASP.Net MVC html helper it will get converted to a string value):

<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中有类似的方法吗?

How do I access rootVar in an angular2 component? I used to use the window service in angular 1.5, is there an analogous way of doing that in angular2?

具体地说,我想使用该rootVar变量来帮助在此组件中生成templateUrl:

Specifically, I want to use that rootVar variable to help generate the templateUrl in this component:

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

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

export class HomeComponent {   
    constructor( ) {  }
}

推荐答案

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

You need to update the file that bootstraps your application to export a function:

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

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

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

Now you can provide the variable from the index.html file this way:

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

然后您可以通过以下方式将rootVar注入组件和服务:

Then you can inject the rootVar into components and services this way:

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

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

这篇关于如何在angular2组件中访问全局js变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆