【问题标题】:rxjs behaviorsubject not changing Ionic 4 viewrxjs behaviorsubject 不改变 Ionic 4 视图
【发布时间】: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


    【解决方案1】:

    试着把这段代码放在构造方法上:

    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.
        });
    

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

    【讨论】:

    • 我不知道在我将那部分添加到我的代码后它会如何工作,你能解释一下吗?
    • 您应该创建一个订阅实例,以便能够接收设备订阅的回调
    【解决方案2】:

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

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

    然后做:

    data: Example [];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2017-11-18
      • 1970-01-01
      • 2021-04-19
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多