【发布时间】:2019-04-23 13:22:31
【问题描述】:
我使用 Ionic 4 制作了一个列表程序,并尝试使用 rxjs 中的BehaviorSubject 更新列表。在ngOnInit() 期间可更新列表,但在add() 回调时列表不会更新。
我尝试记录输出并且订阅方法有效(当我单击添加时,订阅调用),但 Ionic UI 不会更新数据。这是我的代码:
设备管理.service.ts
export class DeviceManagementService {
devices = new BehaviorSubject([]);
constructor(
private storage : Storage
) { }
list() {
this.storage.get('device-list')
.then( d => {
if(d==null) this.devices.next([]);
else this.devices.next(d);
})
.catch(e => { console.log(e) });
}
save(){
console.log("saving to storage",this.devices.value);
this.storage.set('device-list',this.devices.value);
}
add(device){
let x = [].concat(this.devices.value);
x.unshift(device);
this.devices.next(x)
this.save();
}
...
page.ts
...
data = [];
ngOnInit() {
if(!this.auth.loginStatus.logged.value) this.router.navigateByUrl('/');
this.devices.list();
this.devices.devices.subscribe( devices => {
this.data = devices;
console.log("this.data",this.data); // here i log the subscribe.
// it also calls on addBtn() , but Ionic View not updating.
});
}
ngOnDestroy() {
this.devices.devices.unsubscribe();
}
addBtn() {
this.devices.add( { id:1 , nama:"test" } );
}
...
page.html
...
<ion-item *ngFor="let d of data">
<ion-label>
<h1>{{d.nama}}</h1>
<h2>{{d.id}}</h2>
</ion-label>
<ion-icon name="settings" slot="end" (click)="presentActionSheet()">
</ion-icon>
</ion-item>
<ion-button expand="block" (click)="addBtn()">
<ion-icon name="add-circle-outline"></ion-icon>
add device
</ion-button>
...
我哪里做错了,所以我的 Ionic 4 视图没有更新?
已解决:我重新启动我的ionic serve,它就可以工作了。
【问题讨论】:
标签: angular ionic-framework rxjs ionic4