2017-08-24 46 views
0

我有一個項目,我正在使用Ionic2/Cordova Plugins/Android如何使用點符號來調用Cordova插件?

$ mkdir stackoverflow-question 
$ cd stackoverflow-question 
$ git clone https://github.com/napolev/stackoverflow-question.git . 
$ npm install 
$ ionic platform add android 
$ ionic run android -l 

該項目正常工作。它基本上是一個Hello World項目。當您點擊屏幕上的按鈕時,您會收到由Cordova插件返回的消息Hello, World

我的問題是,上線17

https://github.com/napolev/stackoverflow-question/blob/75ecff023a250e14752762582a078d038957c89a/src/pages/home/home.ts#L17

我想使用:

window.hello.greet(...)

,而不是

window["hello"].greet(...)

但是當我使用:window.hello.greet(...)我得到的錯誤:

Property 'hello' does not exist on type 'Window'. 

正如你可以在下面的圖片上看到:

enter image description here

如何使用點符號使用任何想法,自定義Cordova插件?

[編輯1]

按照他的意見@sebaferreras建議,我在下面的方式改變了代碼,並可以正常工作:

import { Component } from "@angular/core"; 
import { NavController } from "ionic-angular"; 

@Component({ 
    selector: "page-home", 
    templateUrl: "home.html", 
}) 
export class HomePage { 

    private window: any = window; 
    private greet: string; 

    constructor(
     public navCtrl: NavController, 
    ) {} 

    private doGreet() { 
     this.window.hello.greet("World", (message) => { 
      this.greet = message; 
     },() => { 
      this.greet = "[ERROR]"; 
     }); 
    } 
} 

,但我想知道:

  1. 這是一個很好的做法:private window: any = window;

  2. 是否還有其他類型比any更具體,我可以在上面的行上使用?

回答

1

由於該錯誤只是打字稿抱怨什麼都不知道一個hello財產在window對象,你可以投的window對象any這樣的:

(<any>window).hello.greet(...) 

編輯

如果你想避免演員陣容到any,你可以創建自己的課程,基於Window類是這樣的:

export interface IGreetingService { 
    greet(): void; // Here you can add any function signature 
} 

export class CustomWindow extends Window { 
    hello: IGreetingService; 
} 

然後,你可以使用這樣的:

(<any>CustomWindow).hello.greet(...) 

或者

private window: CustomWindow = window; // The cast is being done here! 
this.window.hello.greet(...) 
+0

謝謝,它的工作原理。但是我有兩個小問題:1-是一個好習慣:'private window:any = window;'?2-是否有任何其他類型比上一行中可以使用的更多? – davidesp

+0

我已經更新了答案。對於1.而言,由於'window'是一個全局對象,因此將它分配給組件的屬性並沒有多大意義(如果只在一個屬性中使用'hello'屬性,那麼在這種情況下,單身)。關於2.,請在上面的答案中查看更新:) – sebaferreras

0

通常你使用自定義插件,離子/科爾多瓦是這樣的: 添加以下行在您文件的頂部:

declare var NameOfTheJsModule 

您可以在插件的plugin.xml中的name屬性下的JS-模塊的名稱:

<js-module src="www/inappbrowser.js" name="inappbrowser"> 
    ... 
</js-module> 

所以在這種情況下:

delcare var inappbrowser; 

,並使用它例如:

this.inappbrowser.show(); 
相關問題