我用Ionic创建了一个小手机应用程序。我正在尝试实现一个位逻辑,组件知道它何时在线或离线。为此,我使用的是Ionic的网络插件,它只是没有按预期工作。
而不是更新
this.connected
每当我打开/关闭网络时,值都会出现,只有当我关闭/打开它时才会这样做,并做一些事情,比如从横向切换到纵向模式,或者在不同的应用程序上工作一段时间然后回来到应用程序。
真的很困惑。
以下是代码:
import {Component} from '@angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GooglePlus} from '@ionic-native/google-plus';
import {SurveyService} from "./survey.service";
import {Survey} from "../../Declarations/Survey";
import {SurveyPage} from "../survey/survey";
import {Network} from "@ionic-native/network";
@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [SurveyService, Network]
})
export class HomePage {
public surveys: Survey[] = [];
public connected;
public networkType;
constructor(public navCtrl: NavController,
private googlePlus: GooglePlus,
private surveyService: SurveyService,
public navParams: NavParams,
platform: Platform,
private network: Network) {
this.checkForNetwork();
this.surveyService.getAvailable().subscribe(surveys => {
this.checkForNetwork();
this.surveys = surveys;
})
}
login() {
this.googlePlus.login({
'webClientId': '632130231957-dmjd154jhq1eenimedri3m0de6sh7tln.apps.googleusercontent.com'
}).then((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}
logout() {
this.googlePlus.logout().then(() => {
console.log("logged out");
});
}
openSurvey = (survey: Survey) => {
this.navCtrl.push(SurveyPage, {
survey: survey
});
}
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
}
}, 3000);
});
}
}
答案 0 :(得分:0)
好的,我解决了这个问题:
事实证明离子的效果非常好,但我试图根据是否
更改应用程序的视图this.connected
是真还是假。我没有意识到我需要通过使用Application
告诉Angular刷新它的视图applicationRef.tick();
在正确的地方。所以基本上,一旦Ionic改变了this.connected的值,你需要告诉Angular它,这里是代码的更正部分:
您需要将ApplicationRef注入构造函数
constructor(public navCtrl: NavController,
...
private appReference: ApplicationRef) {
...
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
this.appReference.tick();
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
this.appReference.tick();
}
}, 3000);
});
}