简体   繁体   English

推送到角度的可观察变量

[英]push to observable variable in angular

How would I add an extra object to a collection which has been initially subscribed to an observable from the template. 我如何将一个额外的对象添加到最初已从模板预订到可观察对象的集合中。 So I have a variable in my component which is an observable and then I do some http request and set the observable to this service request like so... 所以我在组件中有一个可观察的变量,然后执行一些http请求,然后将可观察者设置为该服务请求,如下所示...

logs$: Observable<any>;

this.logs$ = this.service.getLogs(searchCriteria);

.. then in the template I am subscribing to this observable using async pipe. ..然后在模板中,我使用异步管道订阅了这一可观察的内容。

<div *ngIf="logs$ | async as logs; else loading">

After this data is loaded there is some functionality to then add a new log and I want to then push this new log to the collection to display once it has been saved. 加载此数据后,有一些功能可用于添加新日志,然后我希望将其保存到集合后显示。 Can I push a new value to this observable and reopen the subscription to it or do I need to manually subscribe to this in the component and have the collection there so then I can push to it in the component. 我可以将新值推送到该可观察值并重新打开对其的订阅,还是需要在组件中手动订阅此值并在其中拥有集合,以便可以在组件中推送到它。 Thanks in advance. 提前致谢。

Is this.service.getLogs returing http call observable? 重现http呼叫的this.service.getLogs是否可观察? If so, you are out of luck as http observables are terminated after execution (unles you use pipe share() into them). 如果是这样,您很不走运,因为HTTP可观察变量在执行后终止(除非您在其中使用管道share())。

If I were you, I would keep logs as separate collection. 如果您是我,我会将日志保留为单独的集合。 In such scenario I am free to modify that collection and it will be reflected by UI without any tricks. 在这种情况下,我可以自由地修改该集合,并且该集合将通过UI反映出来而没有任何技巧。

What I would do 我会怎么做

this.logs:Array<Logs>; //declaration
this.service.getLogs(searchCriteria).subscribe(result=>logs=result); // execution in onInit

and to add log on demand 并按需添加日志

this.logs.push(newLog);

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

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