rxjs behaviorsubject 不改变 Ionic 4 视图

rxjs behaviorsubject not changing Ionic 4 view

我使用 Ionic 4 制作了一个列表程序,并尝试使用来自 rxjsBehaviorSubject 更新列表。列表可在 ngOnInit() 期间更新,但列表不会在 add() 回调时更新。

我尝试记录输出并且订阅方法有效(当我点击添加时,订阅被调用),但是 Ionic UI 不会更新数据。这是我的代码:

设备-management.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 并且它正常工作。

尝试将此代码放在构造方法上:

import {Subscription} from 'rxjs';
subscription: Subscription; // this is a local variable

..........

this.devices.list();
    this.subscription = 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.
    });

您的应用程序日志显示什么?

尝试将您的 data = [] 数组更改为具有预定义属性 nameid 的数组。例如,您可以创建:

export class Example {
  nama: string;
  id: string;
}

然后做:

data: Example [];