How to subscribe to an array change?

I am wondering if it is possible to subscribe to the change object, i.e. to an array. My use case: the user reloads the page, which requires loading the entire collection, and then receives one object with a specific identifier. As I know, I can create a function like this:

In the constructor:

this.getById(id); 

And function

 getById(id: string){ this.object = this.objectsService.getById(id); if (this.object.name){ //check if object exist //Do something } else { setTimeout(()=>{ this.getById(id) }, 1000); } } 

However, I got the feeling that this is not the best thing. So, what I would like to do is something like this:

 let objects = this.objectService.getObjects() // returns object that will hold the collection; objects.subscribe((value) => { if(value.length) { //Do something } }); 
+6
source share
2 answers

You can save a link to your array instead of observed . For example, when a call from the http service returns with an Observable , you can do

 function getObjects:Promise<Item[]>{ return this.http.get(this.apiUrl) .toPromise() .then(this.extractData) } private extractData(res: Response) { let body = res.json(); return body.data || { }; } 

In your component class, you can store data as follows:

 this.objectService.getObjects().then(items=> this.items = items); 

Then, when you need to get the element by id , you can do:

 let currentItem = this.items.filter(x=> x.id == currentId) 

That way, you have a cache list when your page loads and it matters when a user's choice changes.

+1
source

If I understand your question correctly, are you looking for creating an observable from an array so you can subscribe to it? If so, you can search for Rx.Observable.from(iterable, [mapFn], [thisArgs],[scheduler] . This article has a rxjs docs page.

It creates an observable from an array that you can subscribe to.

Something like this might be what you are looking for

  Rx.Observable.from([1,2,3]).subscribe(x => // do something with x); 

Sign up for an array change

As stated in the comments, the above approach subscribes to the array and observes the values ​​that are currently in the array, but it has nothing to do with changes to this array.

Perhaps there would be an approach to creating the subject and observing the subject. Instead of clicking values ​​on existing arrays, you push values ​​into an object (which contains basically an array of elements). When you click on a topic, you generate an event that can be captured by the subscriber.

+4
source

All Articles