Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

javascript - 重新分配Observable Array时订阅服务器未更新,但将对象推送到数组时通知该订阅者(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?(每当我将项目推送到数组时,列表都会在View中更新,但是当我对该数组执行过滤功能时,列表是否不会更新?) 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.(搜索工作正常。)   ask by River CR Phoenix translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 演示)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...