插件:
cordova plugin add cordova-plugin-networkinterface
法典:
networkinterface.getIpAddress((ip) => {
console.log(ip);
});
错误:
TypeError: Cannot read property 'getIPAddress' of undefined
现在这里我既没有提供任何提供程序,也没有提供任何导入,那么它在 ionic 2 中是如何工作的呢?
它不是原生插件。但是这个插件也在离子 2 中工作,根据这个链接
Package.json :
{
"name": "ionic-hello-world",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"@angular/common": "2.4.8",
"@angular/compiler": "2.4.8",
"@angular/compiler-cli": "2.4.8",
"@angular/core": "2.4.8",
"@angular/forms": "2.4.8",
"@angular/http": "2.4.8",
"@angular/platform-browser": "2.4.8",
"@angular/platform-browser-dynamic": "2.4.8",
"@angular/platform-server": "2.4.8",
"@ionic-native/core": "3.1.0",
"@ionic-native/in-app-browser": "^3.4.2",
"@ionic-native/network": "^3.4.2",
"@ionic-native/splash-screen": "3.1.0",
"@ionic-native/status-bar": "3.1.0",
"@ionic-native/toast": "^3.4.4",
"@ionic/app-scripts": "^1.2.2",
"@ionic/storage": "2.0.0",
"ionic-angular": "2.3.0",
"ionic-native": "^2.9.0",
"ionicons": "3.0.0",
"rxjs": "5.0.1",
"sw-toolbox": "3.4.0",
"zone.js": "0.7.2"
},
"devDependencies": {
"@ionic/app-scripts": "1.2.2",
"typescript": "2.0.9"
},
"cordovaPlugins": [
"cordova-plugin-whitelist",
"cordova-plugin-statusbar",
"cordova-plugin-console",
"cordova-plugin-device",
"cordova-plugin-splashscreen",
"ionic-plugin-keyboard"
],
"cordovaPlatforms": [],
"description": "Test"
}
最新代码文件:
declare var networkinterface: any;
@Component({
templateUrl: 'app.html'
})
export class MyApp {
public rootPage:any = HomePage;
constructor(private platform: Platform,private statusBar: StatusBar,private splashScreen: SplashScreen, private network: Network, private iab: InAppBrowser, private http: Http, private toast: Toast) {
platform.ready().then(() => {
networkinterface.getWiFiIPAddress((ip) => {
console.log(ip);
});
}
安装非原生插件后,您必须像下面这样使用它。
此方法 (
getIpAddress()
( 已弃用,并使用getWiFiIPAddress()
方法。
declare let networkinterface: any;
@Component({
...
})
export class TestPage {
...
getIpAddress() {
networkinterface.getWiFiIPAddress((ip) => {
console.log(ip);
});
}
}
您可以尝试使用外部网址:
async function getIP(){
const repsIP = await fetch('https://api.ipify.org/?format=json');
const data = await repsIP.json();
return data;
}
无论你想要什么,调用这个函数:
this.getIP().then(data => this.ipAddress = data.ip);