我有一个cordova应用程序,我已经安装了一些插件,如device,appversion。在设备准备就绪这些插件返回一些全球variables
像device
。对于UI代码,我使用角度7。
我怎样才能在角度分量内使用cordova变量?
如果在角度侧有任何变量声明,那么我想只在一个文件中执行此操作,并希望在整个角度应用程序中使用该文件。
通过将来自cordova的所有全局变量存储到root中共享的服务来实现此目的的最佳方法。
在你的app.component
或你的根组件中,声明这些变量:
//Use "declare" to have variables that store cordova and pluggins before Component declaration
declare var StatusBar: any;
declare var cordova: any;
declare var window:any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
在组件构造函数中注入一个存储细节的服务:
//In constructor you inject a service (you can call it cordovaService)
cosntructor(private cordovaService:CordovaService){}
你必须添加ngAfterViewInit
并添加document.addEventListener('device ready')
ngAfterViewInit() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
}
在onDeviceReady
,您可以处理和存储与cordova相关的东西:
onDeviceReady() {
this.cordovaService.cordova=cordova;
cordova.getAppVersion.getVersionNumber().then(appVersion => {
console.log(appVersion);
});
}
现在任何注入CordovaService
的组件都能够访问和使用这个数据/变量。