Cordova application using Angular 2

只谈情不闲聊 提交于 2019-11-28 01:23:40

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'

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!