簡體   English   中英

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

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

我只有一個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);
}

我想將其添加到Angular應用程序的home組件中。

由於我的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;
        });
    }

}

我的問題是在應用程序中包含小型JS函數的最佳方法是什么?

  1. 是否可以在.ts中內聯添加JS函數?

  2. 如果我import { SideModal } from '../../assets/js/sidemodal.js';導入JS文件import { SideModal } from '../../assets/js/sidemodal.js'; 為什么這樣說, but '--allowJs' is not set.

  3. 在Angular打字稿文件中包含自定義JS函數的最佳實踐是什么?

歡迎有任何見識。 謝謝。

如果您可以在組件內部聲明函數,那么所有問題都將得到解決。 您可以像使用組件的任何其他功能一樣使用

如果不能,那么最好的方法是將其添加到標記腳本下的.angular-cli.json文件中,以便cli在加載應用包之前為您加載。

並在類型腳本中使用它,您應該在@Types下搜索Definition Type或編寫自己的類型文件。

一旦您的類型可用:

import {sidemodalclose} from 'your-type';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM