【发布时间】:2018-02-28 01:29:22
【问题描述】:
我正在学习 ionic2。我正在使用 网络连接。我从这个链接 Ionic2 Network Connection 引用了代码。但是我没有收到任何日志或来自 OnConnect() 的警报和 onDisconnect() 方法。
.ts 文件(代码)
import { Component } from '@angular/core';
import { NavController, NavParams, IonicPage } from 'ionic-angular';
import { ToastController } from 'ionic-angular';
import { Http } from '@angular/http';
import { LoadingController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { NativeStorage } from '@ionic-native/native-storage';
import { AlertController } from 'ionic-angular';
import { Ionic2RatingModule } from 'ionic2-rating';
import 'rxjs/add/operator/map';
import { Network } from '@ionic-native/network';
@IonicPage()
@Component({
selector: 'page-outlet',
templateUrl: 'outlet.html',
})
export class OutletPage {
constructor(private storage: Storage,public navParams: NavParams,public alertCtrl: AlertController,public http: Http,public loadCtrl: LoadingController,public toastCtrl: ToastController,public nativeStorage: NativeStorage, public nav: NavController,private network: Network) {
this.loaddata();
var networkState = this.network.type;
let alert1 = this.alertCtrl.create({
title: "Connection Status",
subTitle: networkState,
buttons: ["OK"]
});
alert1.present();
// watch network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
console.log('network was disconnected :-(');
});
// stop disconnect watch
disconnectSubscription.unsubscribe();
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
console.log('network connected!');
// We just got a connection but we need to wait briefly
// before we determine the connection type. Might need to wait.
// prior to doing any api requests as well.
setTimeout(() => {
console.log(this.network.type);
if (this.network.type === 'wifi') {
alert('we got a wifi connection, woohoo!');
}
}, 3000);
});
// stop connect watch
connectSubscription.unsubscribe();
}
loaddata(){
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.get("http://aryvartdev.com/reload/api/ApiController/categorylist",headers)
.map(res => res.json())
.subscribe(data => {
this.rescall=data.message.product_category;
console.log("-this-"+JSON.stringify(this.rescall));
this.rows = Array.from(Array(Math.ceil(this.rescall.length / 2)).keys());
this.rowsLen=this.rows.length;
console.log("row--len--"+this.rowsLen);
}, error => {
console.log(error);// Error getting the data
});
}
}
我在我的 .ts 构造方法中提供了这段代码,它工作正常。它只会显示网络类型。
谁能帮助我为什么这两种方法不起作用?
【问题讨论】:
-
你能把你的完整代码放上去吗
-
是的,我会更新我的代码
-
@NandhiniB 问题是你调用了 stoped connect watch 方法。所以它不起作用,您需要删除停止的连接监视方法
disconnectSubscription.unsubscribe()和`connectSubscription.unsubscribe(); ` -
谢谢...是的,删除这些 disconnectSubscription.unsubscribe() 和 `connectSubscription.unsubscribe();
标签: angular ionic2 network-connection