简体   繁体   中英

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

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? If so, you are out of luck as http observables are terminated after execution (unles you use pipe share() into them).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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