kron3
kron3

Reputation: 3

rxjs behaviorsubject not changing Ionic 4 view

I make a list program using Ionic 4 and I try to update the list using BehaviorSubject from rxjs. The list available to update during ngOnInit(), but the list won't update on add() callback.

I try to log the output and the subscribe method works (when I click add, the subscribe called), but Ionic UI won't update the data. Here is my code :

device-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>
...

Where do I do wrong so my Ionic 4 view not updating?


SOLVED: I restart my ionic serve and it just works.

Upvotes: 0

Views: 871

Answers (2)

benra
benra

Reputation: 396

Try changing your data = [] array to an array with predefined properties name and id. For example you could create:

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

And then do:

data: Example [];

Upvotes: 0

Try to put this code on the constructor method:

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

What are your application logs showing?

Upvotes: 1

Related Questions