且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Observable中的更改未反映在View中

更新时间:2023-02-12 10:11:46

我怀疑问题出在您的呼叫方式上:

I'm suspicious the problem is in the way you call:

this.items.next(this.item.getValue().push(newItem));

我不知道this.item.getValue()返回什么,但是如果push()方法与

I don't know what this.item.getValue() returns but if push() method is the same as Array.push() it returns new length (the important thing is it doesn't return this.items with the new item appended).

async管道定义为:

异步管道订阅了一个Observable或Promise,并返回它发出的最新值.

因此,当您调用this.items.next(...)时,异步管道将仅接收新长度,并尝试使用*ngFor进行迭代.

So when you call this.items.next(...) the async pipe receives just the new length and tries to iterate it with *ngFor.

如果this.item持有<List<Item>>,则您可能想致电:

If this.item holds <List<Item>> then you probably want to call:

this.item.getValue().push(newItem);
this.items.next(this.item);

顺便说一句, asObservable() 方法是用于隐藏您正在使用Subject的事实.让我们调用next()complete(),这是您不希望其他用户惹的祸.因此,***只将Observable传递到所有地方,并只在需要的地方为自己保留Subject.

Btw, the asObservable() method is used to hide the fact that you're working with Subject. Subject let's you call next() or complete() which is something that you don't want other users to mess with. For this reason it's better to pass everywhere just an Observable and keep Subject only for yourself where you know you need it.