我正在尝试列出活动设备。将此信息保存在实例变量screens
中。每当我使用setTimeOut
进行更改时,它都起作用,但是,如果我在callback
部分中进行了更改,则它不起作用。
这是代码:
import { Component } from "@angular/core";
import { NavController } from "ionic-angular";
import { Zeroconf } from '@ionic-native/zeroconf';
@Component({
selector: "page-home",
templateUrl: "home.html"
})
export class HomePage {
screens: Array<{name: any, ip: any}> = [];
constructor(public navCtrl: NavController, private zeroconf: Zeroconf) {
this.screens.push({
name: "TEST",
ip: "123"
})
setTimeout(() => {
this.screens.push({
name: "TEST2",
ip: "Test2"
})
}, 1000);
setTimeout(() => {
this.screens.push({
name: "TEST3",
ip: "Test3"
})
}, 2000);
setTimeout(() => {
this.screens.push({
name: "TEST4",
ip: "Test4"
})
}, 10000);
this.zeroconf.watch('_http._tcp.', 'local.').subscribe(result => {
if (result.action == 'added') {
this.screens.push({ //This is not working
name: result.service.name,
ip: result.service.ipv4Addresses
});
setTimeout(() => {
this.screens.push({
name: result.service.name,
ip: result.service.ipv4Addresses
});
}, 1000);
} else {
console.log('service removed', result.service);
}
});
}
}
这可能是什么原因?
答案 0 :(得分:0)
可能您需要一个BehaviorSubject来定期对其进行更新
在共享服务中定义
listOfScreens: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]);
addScreens(newData) {
this.listOfScreens.next(this.listOfScreens.getValue().concat([newData]));
}
以及您的组件
ngOnInit() {
this.sharedService.listofScreens.subscribe(
screens => this.screens = screens
)
}
addScreens() {
let data = {
name: "TEST",
ip: "123"
}
this.sharedService.addScreens(data);
}