mikhail-t
mikhail-t

Reputation: 4221

Ionic native device plugin @ionic-native/device returns all nulls

I need to do a device detection in my Ionic project so I've installed @ionic-native/device plugin per instructions here: https://ionicframework.com/docs/native/device/

However when I wire it in inside of a component, then run ionic serve to preview changes, console.log returns Device object with all values set to null, same happens when I try to use individual property e.g. this.device.model: console.log output

Here is how I use it inside of a component:

import {Device} from "@ionic-native/device";
// ...

@Component({
    // ...
})
export class MyComponent {

    constructor(private device: Device) {
    }

    ngOnInit() {
        console.log(this.device);
    }

}

And I've added it to AppModule as well:

import {Device} from "@ionic-native/device";
// ...

@NgModule({
    // ...
    providers: [
        Device
    ]
})
export class AppModule() {
}

Cordova device plugin was auto injected into config.xml:

<?xml version='1.0' encoding='utf-8'?>
<widget <!-- ... --> >
    <!-- ... -->
    <plugin name="cordova-plugin-device" spec="2.0.0" />
</widget>

Here is my Ionic stack (at least packages that should be relevant to the issue):

"@angular/*": "^5.2.4",      // all packages
"@ionic-native/*": "4.5.2",  // all packages

"@ionic-native/device": "4.5.2"
"ionic-angular": "3.9.2",
"cordova-plugin-device": "2.0.0",
"typescript": "2.6.2"

Thanks!

UPDATE:

I was able to get device details in the browser by running:

cordova run browser

This assumes you have added browser as a platform, if not run:

ionic cordova platform add browser

(From the link in the answer posted by @AndrewLively: https://stackoverflow.com/a/49034015/448816)

Upvotes: 1

Views: 3998

Answers (2)

Should see the packages installed and see they are in the same version in "package.json"

enter image description here

Core and Native packages must be in the same version or the native package should not be larger.

enter image description here

The folder "platforms" must be delete

enter image description here

Use these commands

    ionic build

    ionic cordova platform add browser

    cordova run browser

code for .ts

console.log('Device Model is: ' + this.device.model);

And works !

enter image description here

Upvotes: 1

Andrew Lively
Andrew Lively

Reputation: 2153

If you are running in the browser using ionic serve then most of the ionic-native plugins won't work since it is not treated by ionic as a valid browser platform.

This is not well documented, but is discussed in an issue in the ionic-native repo.

Upvotes: 2

Related Questions