我的Angular应用程序中有一个js文件data.js。这个js文件中有一些变量声明,如下所示。
var data = 'test'
现在我必须在我的组件(app.component.ts)中访问这些变量及其值。
我读了一些宣称它们的地方,因为导出使它们成为模块,那些可以在任何地方访问,但我不确定如何做到这一点。
这是我的应用程序的结构。我在assets-> js文件夹中有data.js.我需要修改app.component.ts中的变量值。
我对Angular很新。这甚至可能吗?
随着资产中的文件,我猜你在窗口上声明它。您需要在index.html中包含脚本,然后通过window.data在组件的窗口中访问它。除非您的用例规定,否则这不是推荐的方法。您提到的模块方法是首选方法。
在app.component.ts旁边,创建一个名为data.ts的文件,其中包含:
export let data: string = 'data';
在你的app.component.ts中,使用以下方法导入它:
import { data } from './data.ts';
如果您打算不改变该数据,请考虑使用const关键字(在data.ts中)。
目录结构
/app.component.ts
/data.ts
/...
编辑:显示全局方法
您需要在Angular应用程序的上下文之外包含脚本。如果使用Angular CLI引导应用程序,则可以在cli配置文件中添加对它的引用。请参阅topic上的此文档。
该文件将被包含在内,并可在窗口中的组件中访问。棘手的部分来自typing and the Window。示例可能看起来像这样。
class AppComponent extends Component {
private data: string;
constructor() {
// Explicitly cast window as an any type. Would be better to type this, but this should work for you.
this.data = (<any>window).data;
}
}
您希望变量是Component类的成员,而不仅仅是在模块中的任何位置声明的变量。
如果这没有意义,你需要更仔细地查看一些基本的Angular代码示例。
此外,只要您使用Angular并因此使用TypeScript,使用let
或const
的声明变量就更好了。