Reputation: 231
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
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
share
, each subscriber will make one request each).data
array0
(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
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