简体   繁体   English

将外部JS文件添加到Angular 5 CLI

[英]Adding an external JS file to Angular 5 CLI

I have this just one Javascript function: 我只有一个Javascript函数:

function sidemodalclose() {
    $("#sidemodal").modal('hide');
    var date = new Date();
    date.setDate(date.getDate() + 1);
    document.cookie = "visited=yes; path=/; expires=" + date.toUTCString();
    console.log(document.cookie);
}

which I want to add to the home component of an Angular app. 我想将其添加到Angular应用程序的home组件中。

As my home.component.ts has some jQuery functions which need to access the sidemodalclose() function. 由于我的home.component.ts有一些jQuery函数,需要访问sidemodalclose()函数。

import { Component, OnInit } from '@angular/core';

declare var $:any;

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

    constructor() { }

    ngOnInit() {

        $("#no-thanks").click(function() {
            sidemodalclose();
        });

        if (document.cookie.indexOf("visited") == -1) {
            setTimeout(function() {
                $("#sidemodal").modal('show');
            }, 1000)
        }

        $("#submit3").click(function() {
            $("#submit3").html("Just a sec!");
            $.post("https://thirdparty.com/api.php", $("#contact3").serialize(), function(response) {
                $("#submit3").html(response);
            });
            return false;
        });
    }

}

My question is what is the best way to include the small JS function in the app? 我的问题是在应用程序中包含小型JS函数的最佳方法是什么?

  1. Is it possible to add JS functions inline in .ts? 是否可以在.ts中内联添加JS函数?

  2. If I import the JS file with import { SideModal } from '../../assets/js/sidemodal.js'; 如果我import { SideModal } from '../../assets/js/sidemodal.js';导入JS文件import { SideModal } from '../../assets/js/sidemodal.js'; why does it say but '--allowJs' is not set. 为什么这样说, but '--allowJs' is not set. ?

  3. What is the best practice to include custom JS functions in Angular typescript file? 在Angular打字稿文件中包含自定义JS函数的最佳实践是什么?

Any insight is welcome. 欢迎有任何见识。 Thanks. 谢谢。

If you can declare your function inside your component, all your problems is solved. 如果您可以在组件内部声明函数,那么所有问题都将得到解决。 You can use like any other function of your component using this 您可以像使用组件的任何其他功能一样使用

If you can not, so the best way is to add it to your .angular-cli.json file under the tag scripts so the cli load it for your before your app bundle get loaded. 如果不能,那么最好的方法是将其添加到标记脚本下的.angular-cli.json文件中,以便cli在加载应用包之前为您加载。

And to use it in your type script you should search for Definition Type under @Types or write your own type file. 并在类型脚本中使用它,您应该在@Types下搜索Definition Type或编写自己的类型文件。

Once your type is available: 一旦您的类型可用:

import {sidemodalclose} from 'your-type';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM