我需要从 Angular 项目更新外部 javascript 文件中的变量
首先,我在 Angular 组件中导入变量,然后尝试更新它,但我不知道该怎么做
我的 Angular 组件的小例子:
import { Component } from '@angular/core';
import { externalText } from './external.js';
...
export class AppComponent {
myText = externalText;
changeText() {
// This works, but I need to update the variable from external file directly
this.myText = 'Text updated'
// I need something like this
// externalText = 'Text updated'
}
}
我用一个例子创建了这个 Stackblitz:
https://stackblitz.com/edit/angular-hczxhh
预期:能够从我的 Angular 组件更新 Javascript 文件中的信息
最佳答案
最后,我刚刚在 .js 文件中创建了一个函数,该函数用 Angular 提供的内容覆盖此变量。然后我导出了这个函数以便在 Angular 组件中使用它。
Javascript 文件:
export function updateText(myText) {
externalText = myText
}
Angular 分量:
import { externalText, updateText } from './external.js';
export class AppComponent {
myText = externalText;
changeText() {
updateText('Problem solved')
}
}
非常感谢大家的回答。
关于javascript - 如何从 Angular/Typescript 中的外部 javascript 文件更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57869126/