簡體   English   中英

訪問index.html中定義的變量

[英]Access to variable defined in index.html

在index.html中,我添加腳本並創建對象

       <script>
            let dkrm = new Darkroom('#ocrImg', {
                // Size options
                minWidth: 800,
                minHeight: 800,
                maxWidth: 1000,
                maxHeight: 900,
                ratio: 4/3,
                backgroundColor: '#fff',
            });
        </script>

但是現在我嘗試在Angular ts文件的某些組件中使用此Darkroom

我嘗試

var declare Darkroom: any;

和在

    ngOnInit() { this.darkroom = window["dkrm"];}

但是this.darkroom是不確定的

如何訪問index.html中定義的變量並在.ts文件中使用此var?

更改腳本以直接設置window字段

<script>
    window.dkrm = new Darkroom('#ocrImg', {
        // Size options
        minWidth: 800,
        minHeight: 800,
        maxWidth: 1000,
        maxHeight: 900,
        ratio: 4/3,
        backgroundColor: '#fff',
    });
</script>

您無法訪問在腳本標記中用let定義的變量。

如果要定義全局變量,則必須將其放在window對象中:

<script>
        window.dkrm = new Darkroom('#ocrImg', {
            // Size options
            minWidth: 800,
            minHeight: 800,
            maxWidth: 1000,
            maxHeight: 900,
            ratio: 4/3,
            backgroundColor: '#fff',
        });
    </script>

將數據分配給窗口對象(例如window.darkroom),然后在下面的組件中訪問它。

index.html

<script>
    window.darkroom = {};
</script>

component.ts

darkroom: Object = {};
ngOnInit() {
    this.darkroom = window.darkroom;
}

暫無
暫無

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

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