I am using Angular 2 to build a hybrid app with cordova. I do not use Ionic, so please do not refer to it at all. I use the same Angular code both on the browser and on the mobiles.
I put a folder inside the Angular app which contains the cordova project, and I use a hook script when i call cordova run android to build the Angular app and output it into the www folder.
All of this works perfectly, the app builds successfully and everything works fine, but when I try using plugins, here comes the problem.
My index.html looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Servizio Feste</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="favicon.png">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script type=”text/javascript” src=”cordova.js”></script>
</head>
<body>
<ngx-app></ngx-app>
<style>
.spinner { /* styles */ }
.global-spinner { /* styles */ }
</style>
<div id="nb-global-spinner" class="global-spinner">
<div class="spinner"></div>
</div>
</body>
</html>
And my main.ts:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
I installed the phonegap barcodescanner plugin and I tried to use it in a component as follows:
import { AppToasterService } from './../../../../services/toaster.service';
import { Component } from '@angular/core';
declare var cordova: any;
@Component({
selector: 'qrcode',
templateUrl: './qrcode.component.html'
})
export class QRCodeComponent {
constructor(
private toasterService: AppToasterService
) { }
scanQRCode() {
cordova.plugins.barcodeScanner.scan(result => {
this.toasterService.success(result);
}, error => this.toasterService.error('Error'));
}
}
When I try to call the scanQRCode() method the following error pops up:
ReferenceError: cordova is not defined
I searched a lot on already existing issues in stackoverflow but everyone mentions
declare var cordova: any;
or loading the cordova.js script in index.html but I already did those things. Some others said to import cordova.js in the "scripts" section of .angular-cli.json, but also this I tried and it gave me a compilation error saying that cordova.js was not found. I have also tried to wait for the "deviceready" event in main.ts to bootstrap the app but that event never fires! Could someone help me please ? I thank you in advance.