我想访问angular2组件中的全局javascript变量,反之亦然。我在脚本标记中指定了index.html中的默认值,我可以在angular2组件中读取这个值。但是,当我编辑/重新分配一些其他值到angular2组件中的变量时,我无法访问/获取javascript中已编辑的值。
我在main.ts的时候
export function main(dateColumnName: any)
{
platformBrowserDynamic([{ provide: 'dateColumnName', useValue: dateColumnName }]).bootstrapModule(AppModule)
}在Index.html中,我将导入如下所示
<script>
var dateColumnName = "WEEK_END_DT";//assigned with default value
System.import('app/main').then((module) => {
module.main(dateColumnName);
});
function myFunc()
{
alert(dateColumnName);//I need to access the edited value from here...
}
</script>在我的AppComponent中,我将变量插入构造函数中,如
export class AppComponent{
dateColumnName : any; //Local variable
constructor( @Inject('dateColumnName') _dateColumnName: string)
{
_dateColumnName --> this input parameter contains the value specified in the index.html
}
method1()
{
this.dateColumnName = "NewValue"//This newly assigned value to be accessed in index.html
}我需要在我的angular2组件中重新分配一些值,并使用javascript方法中的值.基本上,我想分享一些价值从angular2到javascript.
我在这里错过了什么?如何重新分配变量?
发布于 2017-06-02 20:16:48
使用窗口对象。在您的index.html中有一个全局变量:
<script type="application/javascript">
var testGlobalVar = 'initial value';
</script>在组件的类中:
import { Component } from '@angular/core';
declare var window: any; //DON'T FORGET ABOUT THIS ONE!!!
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
}
getGlobalVarValue() {
console.log('testGlobalVar: ', window.testGlobalVar);
return window.testGlobalVar;
}
setGlobalVarValue(value: string) {
window.testGlobalVar = value;
return window.testGlobalVar;
}
}和组件的模板/html:
<a (click)="getGlobalVarValue()">get global var value</a>
<br />
<a (click)="setGlobalVarValue('new value from angular2')">set global var value</a>或者,您可以直接访问全局变量,而无需通过window对象:
import { Component } from '@angular/core';
declare var testGlobalVar: any; // WITHOUT WINDOW OBJECT
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
}
getGlobalVarValue() {
console.log('testGlobalVar: ', testGlobalVar);
return testGlobalVar;
}
setGlobalVarValue(value: string) {
testGlobalVar = value;
return testGlobalVar;
}
}为了有一个更好的结构来处理全局属性/变量/方法,我会创建一个单独的服务并注入它(依赖注入)!
发布于 2017-06-03 02:21:15
您可以在组件之间与子父关系或通过服务进行通信。
https://angular.io/docs/ts/latest/cookbook/component-communication.html
但有办法通过ngrx/商店。这个概念类似于Redux。你可以试试。
https://stackoverflow.com/questions/44336549
复制相似问题