2017-06-13 85 views
0

任何人都可以幫助我如何從我的angular2組件中的外部js文件調用一個函數。下面是我的代碼片段,當我試圖加載它正在拋出的應用程序App是未定義的錯誤。未定義的錯誤,同時調用角度2中的一個javascript函數

這裏是我的組件代碼:

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

@Component({ 
    selector: 'test', 
    templateUrl: './test.html' 
}) 

export class TestComponent implements OnInit { 

    constructor() { } 

    ngOnInit() { 

    } 

    ngAfterViewInit() { 
     App.handleInit(); 
    } 
} 

這裏是我的內app.js腳本:

var App = function() { 
    var handleInit = function() { 
     console.log("Hello world"); 
    }; 
}(); 

當我們呼籲內ngAfterViewInit它扔應用程序的功能是不確定的錯誤。

我們正在導入app.js文件在vendor.ts中,我們正在使用webpack。 這裏app.js加載正常,但功能不工作。

請幫助我們解決方案。

在此先感謝。

+0

沒有angularjs 2,只是角度 –

+0

我們的意思是Angular2 – Surya

+0

爲您創建的js文件的界面並裝載在你的應用模塊,並訪問您的角2組件內部的方法 –

回答

0

您可以像那樣訪問。這是否幫助

import { Component, OnInit, AfterContentInit } from '@angular/core'; 
import '../../../../js/app.js'; //just example set this based on your path 
declare var App: any; 

@Component({ 
    selector: 'test', 
    templateUrl: './test.html' 
}) 
export class TestComponent implements OnInit { 

    constructor() { } 

    ngOnInit() { } 

    ngAfterViewInit() { 
     this.handleInit(); 
    } 

    hadeleInit() { 
     new app.handleInit(); 
    } 
} 
+0

Hi Shailesh Ladumor, 感謝您的快速響應,但問題是我們的app.js文件(如應用程序)中沒有導出成員,因此我們無法導入您喜歡的內容。還有其他方法嗎? – Surya

+0

你在哪裏添加這個js文件? –

+0

我已經更新了我的答案。你需要導入app.js文件 –

0

你要只是簡單定義應用程序在下面的部分變量

declare var App: any; 
@Component({ 
    ..... 
}) 

現在你的下面的電話會工作。

ngAfterViewInit() { 
    App.handleInit(); 
} 
+0

嗨Sandip,感謝您的迴應,我們嘗試了以上,但仍然得到應用程序是未定義的錯誤。 – Surya

+0

您的JS是否可用於DOM?因爲我已經在幾個組件中嘗試了這種類型的代碼,並且它適用於我 –

+0

是文件正在加載,但函數未調用。我們在vendor.ts中加載js文件,但不在index.html文件中加載。 – Surya

相關問題