嗨,我有一个名为' script.js'的脚本。问题是我有很多函数,我需要在angular的开头执行这个函数。
var appMaster = {
preLoader: function(){
},
smoothScroll: function() {
}
}
但我需要调用此变量appMaster
import '../../assets/js/script.js';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
appMaster.preLoader();
appMaster.smoothScroll();
}
}
错误是appMaster没有未声明的变量。如何在其他脚本中执行这些功能?
答案 0 :(得分:0)
如果要在其他地方使用appMaster变量,则需要从脚本文件中导出该变量。
export let appMaster = {
preLoader: function(){
},
smoothScroll: function() {
}
};
import {appMaster} from '../../assets/js/script.js';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
appMaster.preLoader();
appMaster.smoothScroll();
}
}
答案 1 :(得分:0)
希望您想使用导出/导入语句。
如果是,请更改script.js并使用export
var appMaster = {
preLoader: function(){},
smoothScroll: function() {}
}
export default appMaster;
在组件文件中使用import
import anyName from "./path/to/file";
从script.js,expample
调用任何函数anyName.preLoader()
答案 2 :(得分:0)
试试这样:
在项目资产中的以下位置创建名为common.js的javascript文件=> js =>的script.js
<强> common.js 强>
var comman = (function() {
return {
masonryBuild: function() {
console.log('preLoader');
}
}
})(comman || {})
打开 .angular-cli.json 文件然后添加外部javascript文件路径,如下所示
"scripts": [
"../src/assets/js/comman.js"
]
在你的打字稿中声明脚本var名称,如:
<强> component.ts 强>
declare var comman: any;
export class Component {
ngOnInit() {
comman.masonryBuild();
}
}
答案 3 :(得分:0)
You can call varibale from anthoer script in Angular application.
Step 1. Create demo.js file in assests/javascript folder.
export function test1(){
console.log('Calling test 1 function');
}
Step 2. Create demo.d.ts file in assests/javascript folder.
export declare function test1();
Step 3. Use it in your component
//User defined file path
import { test1 } from '../assets/javascript/demo';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
console.log(test1());
}
}
Note: js and .d.ts file name shoule be same