【问题标题】:Why I cannot use JS file inside Angular app?为什么我不能在 Angular 应用程序中使用 JS 文件?
【发布时间】:2019-12-31 09:49:08
【问题描述】:

我正在尝试将一些 js 方法包含在 Angular 应用程序的文件中。不幸的是,我无法让浏览器看到 js 文件。
我查看了这个 SO 帖子并关注说明,但浏览器看不到文件 (Sources) 部分。



Js 文件

 function  toggleModal(id) {
        var modal = document.getElementById(id);
        $("#" + id).modal('toggle');
    }

    function setPag(tableId) {
        $(tableId).DataTable();
    }

我的文件位于里面:

Root/
  assets/
    js/
      scr.js

在组件中的使用

declare function setPag(id:string):any;
declare function toggleModal(id:string):any;

@Component({
  selector: 'index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
     public toggle(id:string){
        toggleModal(id);
     }
     public setPage(id:string)
     {
        setPag(id);
     }
}

Angular.json
-脚本部分

"architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/AnubisUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/assets"

            ],

            "scripts": [
              "./src/assets/js/scr.js",
              "node_modules/chart.js/dist/Chart.js",
              "node_modules/hammerjs/hammer.min.js"
            ]
          }

【问题讨论】:

    标签: javascript node.js angular typescript ecmascript-6


    【解决方案1】:

    试试这个看看是否适合你

    import * as helper from 'assets/js/scr.js'
    
    @Component({
      selector: 'index',
      templateUrl: './index.component.html',
      styleUrls: ['./index.component.css']
    })
    export class IndexComponent implements OnInit {
         public toggle(id:string){
            helper.toggleModal(id);
         }
         public setPage(id:string)
         {
            helper.setPag(id);
         }
    }
    

    旁注:每个静态文件都应该添加到资产文件夹中,以便您可以导入到您的角度代码中

    【讨论】:

    • 浏览器不加载文件!它不会出现在Sources 部分中。
    • 你需要把你的脚本放到asset文件夹里
    • 我也放到assets里面了,还是看不到。
    • 有什么错误吗?如果还是不行,可以把你的代码上传到 github 让我看看吗?
    • 现在似乎添加到资产中,只有资产才能使它起作用。您可以发布您的答案,我会接受。
    猜你喜欢
    • 2017-05-05
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多