Cordova application using Angular 2

2019-01-15 16:10发布

问题:

Instead of ionic I would like to use cordova framework.

So far,

Step 1:

I have created an angular 2 application.

Step 2:

I have created an cordova application and integrated angular 2 application in it.

Its running successfully.

Step 3:

Next step is to load cordova.js file on load

Step 4:

Add cordova plugin(like camera , device ext) in my project.

Step 1 and 2 completed.

Please help me out to complete step 3 and step 4.

When I call plugin its throws an error as follows,

回答1:

Got an output with following steps,

1)Created an angular project

(Optional)I am using the angular IDE to create angular project

2)Added reference to cordova.js file reference in angular project html file.

<script type="text/javascript" src="cordova.js"></script>

3)Create an cordova project

4)Added platform and plugin to the cordova project.

for my case I added browser platform and cordova device plugin.

5)In angular project implemented OnIt and added the plugin callback function as follow.

Note: It is important to call cordova plugin after 'onDeviceReady'

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

    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit{

    ngOnInit() {
        document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
           alert(device.platform);
        }
    }

    }

6)Typescript does not recogonise 'device.platform' and warns as cannot find device

To resolve this issue add the line 'declare var device;'

After adding the above my AppComponent.ts file looks like follows,

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

declare var device;

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

ngOnInit() {
    document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
           alert(device.platform);
        }
}

}

7)Build the angular project and copy the build files into cordova /www folder

I am using the script to copy file from angular project to cordova. Tutorial here

8)Prepare and run the cordova project.

for my case I ran the cordova project in browser and got an alert with value 'Browser'



回答2:

When are you calling the plugin - are you waiting for onDeviceReady to fire?



回答3:

It's not an official solution but you can bootstrap your angular 2,4 with onDeviceReady event listener on maint.ts and then all your application will run when event is fired. Ex:

 document.addEventListener("deviceready", () => {
  platformBrowserDynamic().bootstrapModule(AppModule);
 }, false);