2016-05-20 30 views
8

Có cách nào chính xác để gọi hàm JavaScript từ một thành phần trong Angular 2 (TypeScript) không?Angular 2 typescript gọi hàm javascript

Đây là thành phần của tôi:

import { ElementRef, AfterViewInit }  from '@angular/core'; 

export class AppComponent implements AfterViewInit { 

    constructor(private _elementRef: ElementRef) { 
    } 

    ngAfterViewInit() { 
     /** 
     * Works but i have this error : 
     * src/app.component.ts(68,9): error TS2304: Cannot find name 'MYTHEME'. 
     * src/app.component.ts(69,9): error TS2304: Cannot find name 'MYTHEME'. 
     */ 
     MYTHEME.documentOnLoad.init(); 
     MYTHEME.documentOnReady.init(); 

     /** 
     * Works without error, but doesn't seem like a right way to do it 
     */ 
     var s = document.createElement("script"); 
     s.text = "MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init();"; 
     this._elementRef.nativeElement.appendChild(s); 
    } 
} 

Gọi hàm JavaScript trực tiếp gây ra một lỗi biên dịch, nhưng cú pháp trong "biên soạn" tập tin JavaScript (app.component.js) là chính xác:

AppComponent.prototype.ngAfterViewInit = function() { 
    MYTHEME.documentOnLoad.init(); 
    MYTHEME.documentOnReady.init(); 
}; 

Cách thứ hai (appendChild) hoạt động mà không có lỗi, nhưng tôi không nghĩ (thay đổi DOM từ kiểu chữ/góc) là cách chính xác để thực hiện.

Tôi thấy điều này: Using a Javascript Function from Typescript tôi đã cố gắng tuyên bố giao diện:

interface MYTHEME { 
    documentOnLoad: Function; 
    documentOnReady: Function; 
} 

Nhưng nguyên cảo dường như không nhận ra nó (không có lỗi trong việc kê khai giao diện).

Cảm ơn

Edit:

Tiếp theo câu trả lời của Juan Mendes đây là những gì tôi đã kết thúc với:

import { AfterViewInit }  from '@angular/core'; 

interface MYTHEME { 
    documentOnLoad: INIT; 
    documentOnReady: INIT; 
} 
interface INIT { 
    init: Function; 
} 
declare var MYTHEME: MYTHEME; 

export class AppComponent implements AfterViewInit { 

    constructor() { 
    } 

    ngAfterViewInit() { 
     MYTHEME.documentOnLoad.init(); 
     MYTHEME.documentOnReady.init(); 
    } 
} 

Trả lời

7

Bạn phải nói nguyên cảo về bên ngoài (JavaScript) tờ khai sử dụng declare. Xem https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html

interface MyTheme { 
    documentOnLoad: Function; 
    documentOnReady: Function; 
} 
declare var MYTHEME: MyTheme; 

Hoặc nặc danh

declare var MYTHEME: {documentOnLoad: Function, documentOnReady: Function}; 
+0

Cảm ơn, nó hoạt động! – Joshua

+0

@Joshua bạn có thể làm cho các bước nhỏ hơn, như mới cho bản thảo, tìm cách gọi hàm js từ tệp js bên ngoài bên trong các thành phần –

+1

@MBalajivaishnav Câu trả lời của tôi không phải là nơi để bạn đặt câu hỏi không liên quan. Vui lòng xóa nhận xét này và thêm một câu hỏi mới, chúng tôi không tái chế các câu hỏi tại đây để mỗi câu hỏi có thể có bài đăng riêng để có thể hữu ích nhất cho người khác. –

Các vấn đề liên quan