简体   繁体   English

订阅者在重新分配 Observable 数组时未更新,但在将对象推送到数组时收到通知

[英]Subscriber not updated when reassigning Observable Array but notified when pushing object to array

I have made an Observable out of an array and i have subscribed to it.我已经从数组中创建了一个 Observable,并且我已经订阅了它。 whenever I push items to an array, the list is updated in View, but when I do a filter function on that array it is not updated?每当我将项目推送到数组时,列表都会在视图中更新,但是当我对该数组执行过滤功能时它不会更新?

The array is a property of a class, it is reassigned on doing array.filter()该数组是一个类的属性,它在执行 array.filter() 时被重新分配

  addUser(user) {
    const newUsers = JSON.parse(window.localStorage.getItem('users'));
    this.users.push(user);
    newUsers.push(user);
    window.localStorage.setItem('users', JSON.stringify(newUsers));
  }

  subscribeUsers(): Observable<any> {
    this.users = JSON.parse(window.localStorage.getItem('users'));
    return of(this.users);
  }

  searchUser(key) {
    let name;
    if (key === '') {
     this.users = JSON.parse(window.localStorage.getItem('users'));
     return;
    } else {
    this.users = this.users.filter(item => {
      name = `${item.name.first} ${item.name.last}`;
      if (name.includes(key)) {
        return true;
      } else {
        return false;
      }
     });
   }
   console.log(this.users);
  }

when addUser() is called, the subscriber is updated, list update in view, but when searchUser() is called, the subscriber is not updated, the list stays same.调用 addUser()时,订阅者被更新,视图中的列表更新,但是当调用 searchUser()时,订阅者没有更新,列表保持不变。 the search is working fine.搜索工作正常。

The issue is from your subscribeUsers method:问题出在您的subscribeUsers方法中:

 subscribeUsers(): Observable<any> {
    this.users = JSON.parse(window.localStorage.getItem('users'));
    return of(this.users);
  }

The subscriber always get the data from local storage before it emits the observable.订阅者总是在发出可观察对象之前从本地存储中获取数据。 So for your filter to work, you'll have to store the results of the filter to local storage.因此,要使过滤器正常工作,您必须将过滤器的结果存储到本地存储中。 Which doesn't make much sense.这没有多大意义。

Your subscriber should just return of(this.users) since you are mutating that array already.你的订阅者应该只返回of(this.users)因为你已经在改变那个数组。

 subscribeUsers(): Observable<any> {
    // remove this line
    // this.users = JSON.parse(window.localStorage.getItem('users'));
    return of(this.users);
  }

EDIT:编辑:

Stackblitz demo Stackblitz演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM