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

北战南征 提交于 2021-01-28 08:51:51

问题


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:

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)


回答1:


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.




回答2:


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

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

The folder "platforms" must be delete

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 !



来源:https://stackoverflow.com/questions/49033577/ionic-native-device-plugin-ionic-native-device-returns-all-nulls

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