2017-09-13 28 views
0

我想在Angular 4中加載動態腳本。腳本本身的名稱稍後將來自Ajax調用。目前要加載我導入Jquery的JavaScript文件到我的Angular項目中。從那以後,我使用getScript加入方法,可以加載該文件,但如果我要調用這樣的功能:在Angular 4中動態加載Javascript腳本

import { Component } from '@angular/core'; 
import * as jQuery from 'jquery'; 

declare var $:any; 
declare var jquery:any; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    title = 'angular 4 with jquery'; 
    url = "currently hardcoded"; 

    getScript42(){ 
     $.getScript(this.url).done(function() { 
     logger(); 
    }); 
    } 
    } 

我收到以下錯誤: 找不到名稱「記錄」

但在我JavaScript文件的功能定義如下:

$(document).ready(function(){ 

    function logger(){ 
    console.log("it worked"); 
    } 
}); 

如果我不使用它的工作功能。

所以,現在我的問題你們知道一種方法來加載該文件並調用特定的功能嗎?

+0

Hi @Henry Sachs任何html模板引用? – 2017-09-13 15:30:34

+0

你問什麼原因?我有一個onclick方法的按鈕。 –

+0

沒有理由我沒有:)!,我只是問這個: \t 您好任何html模板引用? – 2017-09-13 17:07:41

回答

0

在角度生命週期AfterViewInit在視圖加載時調用,這意味着您的html已準備就緒並準備好接受任何其他腳本標記。

所以你可以通過實現接口在你的afterviewinit方法中寫這些。

declare var $:any; 
declare var jquery:any; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent implements AfterViewInit { 

    title = 'angular 4 with jquery'; 
    url = "currently hardcoded"; 

     ngAfterViewInit(): void { 
     $.getScript(this.url).done(function() { 
      logger(); 
     }); 
    } 
    } 
+0

我目前沒有可能嘗試這個,但會回來。 –

+0

所以這仍然不適用於我,我得到相同的錯誤,他無法找到名稱記錄器。 –