我試圖檢查互聯網連接。每當連接丟失時,我想向用戶顯示警報,如果用戶單擊刷新按鈕,我想再次檢查連接...但是當我退訂連接丟失時,我無法再次訂閱。 我做錯了什麼?Angular 2通過按鈕訂閱/取消訂閱
constructor(private alertController: AlertController){
let connection = this.checkConnection().subscribe(data => {
let alert = this.alertController.create({
title: 'Error',
subTitle: "You lost connection !",
buttons: [ {
text: 'Refresh',
handler:() => {
connection.subscribe();
}}]
});
if(data == false){
alert.present();
connection.unsubscribe();
}
}
);
checkConnection() {
return Observable
.interval(500)
.map(() => {
return navigator.onLine;
});
}
UPDATE:
let refresh$ = new Subject();
let connection$ = refresh$.mergeMap(() => {
return Observable
.interval(50)
.map(() => navigator.onLine)
.filter(onLine => !onLine)
.take(1);
});
refresh$.next();
connection$.subscribe(data => {
console.log(data)
})
你在哪裏訂閱? – echonax
處理程序:()=> { connection.resubscribe(); }}]但它沒有工作..任何想法我怎麼能再次訂閱? –
你能告訴我'resubscribe'的api嗎?你在哪裏找到這種方法? – echonax