Marcos
Marcos

Reputation: 231

rxjs observable<entity> (array) count or lenght in typescript (angular 4)

I need to know how much elements are in an array like Observable. I need just to retrive a number, not an Observable. I lost a lot of time trying different operators, without success.

Here's the code:

entities: Observable<entity>;

let data = await this.myService.filter(2)
                    .subscribe(d => {this.entities= d; })

I'm using angular HttpClient, who sends an Observable directement from the response. The service code is very simple:

filter(arg: int): Observable<any> {
    return this.http.get<entity>('/api/ent/find/' + arg.toString());}

The entities Observable is normally loaded, with multiples entities - I use it in a grid -. I just need something like

howMany: number = entities.count() or entities.length()...

to get the quantity to use in the component (not to show). And I got with different ways an Observable, when I need just a number.

Upvotes: 0

Views: 6328

Answers (2)

Jon G St&#248;dle
Jon G St&#248;dle

Reputation: 3904

If I understand you correctly, you have an Observable<entity> which returns an unknown number of results and you want to know that number. Here's one way to do it:

const entitie$: Observable<entity> = this.myService.filter(2).share(); // 1
let data: [entity] = []; // 2
let count: number = 0; // 3

entitie$.subscribe(ent => this.data.push(ent)); // 4
entitie$.reduce((state, curr) => state + 1, 0).subscribe(c => count = c); // 5
  1. This makes the request to your service and shares the resulting observable between all subscribers. (If you don't use share, each subscriber will make one request each).
  2. This is used to store the returned entities.
  3. This will hold the number of entities returned by the observable.
  4. This simply subscribes to the results returned by the request and pushes the received entities into the data array
  5. This will start with the value 0 (as specified in the last parameter). For each new value (curr), it will add one to the stored value (state) and store that new value. When entitie$ completes it will return the stored value, which is the number of returned entities.

Upvotes: 2

Alexander
Alexander

Reputation: 3247

You need to subscribe to the Observable and then you can get the length of the array

entities$: Observable<Entity[]>;
entities: Entity[];
this.myService.filter(2)
                .subscribe(value => this.entities= value);

Then you can use entities.length()

Upvotes: 1

Related Questions