Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get angular Observable stream as array

I have list, that should simulate the stream :

list = [
  {name : 'Str1', age: 10},
  {name : 'Str2', age: 10},
  {name : 'Str3', age: 10}
];

and I've created an Observable from this list:

Observable.from(this.list).skip(this.currentPage * this.pageSize).take(this.pageSize).subscribe(data => this.pagerList = data, console.error);

And in the subscribe method I get the values one by one. How I'm supposed to wait for the whole data to be returned and then to get the whole list. There is take() operator, and after it the Observable have to stop.

I don't want to put every value one by one in the array.

I'm new here, not only for angular, but for javascript as well.

like image 785
makkasi Avatar asked Feb 19 '17 17:02

makkasi


People also ask

How do you declare an observable array?

Subscribing to an observable always return the value of the observable after it emits it. If you want to declare the variable as the observable itself, you simply assign it as the call: this. listeIsolements$ = this.

What is observable array?

ObservableArray is an array that allows listeners to track changes when they occur.

What is .subscribe in Angular?

Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.


2 Answers

Have you tried to use toArray operator?.

let list = [
  { name: 'Str1', age: 10 },
  { name: 'Str2', age: 10 },
  { name: 'Str3', age: 10 },
  { name: 'Str4', age: 10 },
  { name: 'Str5', age: 10 },
  { name: 'Str6', age: 10 }
];

let currentPage = 2;
let pageSize = 2;

Rx.Observable.from(list)
  .skip(currentPage * pageSize)
  .take(pageSize)
  .toArray()
  .subscribe(data => console.log(data), console.error);
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.min.js"></script>
like image 149
yurzui Avatar answered Sep 25 '22 07:09

yurzui


The scan operator should do what you want

Observable.from(this.list)
.skip(this.currentPage * this.pageSize)
.take(this.pageSize)
.scan([], acc, curr) => {acc.push(curr); return acc;});
.subscribe(data => this.pagerList = data, console.error);

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan

like image 44
Günter Zöchbauer Avatar answered Sep 23 '22 07:09

Günter Zöchbauer