Calculating the number of entities in an array using RxJS observable in Typescript (Angular 4)

I'm struggling to figure out how to retrieve the number of elements in an array-like Observable without getting back another Observable. I've spent a lot of time experimenting with different operators, but none have been successful.

Here's my current code snippet:

entities: Observable<entity>;

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

I am using Angular HttpClient, which directly sends an Observable from the response. The service code is quite straightforward:

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

The entities Observable is typically loaded with multiple entities that I use in a grid. All I need is something like

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

To get the quantity for use in the component (not display). However, every approach I've tried has resulted in returning an Observable instead of a simple number.

Answer №1

If my interpretation is correct, you have a situation with an Observable<entity> that may yield an unknown quantity of outcomes and you're interested in determining that quantity. Here's one possible approach:

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

entities$.subscribe(entity => this.results.push(entity)); // 4
entities$.reduce((state, curr) => state + 1, 0).subscribe(num => total = num); // 5
  1. This line sends the request to your service and shares the resulting observable amongst all subscribers. (Without using share, each subscriber will generate its own request).
  2. This variable is utilized for storing the fetched entities.
  3. This variable will keep track of how many entities are delivered by the observable.
  4. This part subscribes to the outcomes from the request and adds the received entities into the results array.
  5. Here, the reduction operation initiates with the value 0 (as set in the last argument). For every new value (curr), it increments the stored value by one and updates it. When entities$ completes, it emits the final count, representing the number of returned entities.

Answer №2

To access the length of the array, you must first subscribe to the Observable.

data$: Observable<Data[]>;
data: Data[];
this.myService.filter(2)
                .subscribe(result => this.data = result);

After that, you can use data.length()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting dates in JavaScript to the format (d MMMMM yyyy HH:mm am) without using moment.js

Looking to convert the date "2020-02-07T16:13:38.22" to the format "d MMMMM yyyy HH:mm a" without relying on moment.js. Here is one method being utilized: const options = { day: "numeric", month: "long", year: "numeric", } var date1 = new Date ...

Setting up Thrift in an Angular and Electron project

Attempting to incorporate Thrift API calls into my Angular application, I used the following command to generate client files: thrift-0.18.1.exe -r --gen js:ts <myService.thrift> The command successfully created both JavaScript (js) and TypeScript ( ...

Angular Toggle Button on multiple lines

I am looking to incorporate several angular toggle buttons in my project. The number of buttons I need will depend on the data from my database. These buttons are displayed on a sidebar, which means that only a maximum of 3 buttons can be shown in one lin ...

Are there alternative methods for writing to a JSON file in Angular without relying on the fs module?

Having trouble with the fs module in Angular 7 because of the error message "can't find module fs" when attempting to write to a JSON file. Any suggestions for alternative solutions would be greatly appreciated. ...

Client side is receiving an unexpected format from the pyramid when using the __json__ method

As I'm configuring a Pyramid back-end along with an Angular front-end application, I encounter an issue. When Angular sends an http GET request to Pyramid, the data received on the Angular side is not as expected. It seems like the id is being recogni ...

Encountering an error during the registration process of @fastify/middie

I am currently in the process of integrating Fastify into a small project I am working on. One of the key requirements for this project is the utilization of Middleware (via @fastify/middie). However, when I follow the necessary steps to register the middi ...

What is the best way to connect an object to an array using ngFor in Angular?

It has been noticed that in Angular, the current variable does not align with the available options. Even though the object { question: 'q3', answer: '' } exists in data.questions, it may not be a direct match. Is there a method to en ...

Discovering the array item by its ID using Angular 2 with Typescript

Hey everyone, I'm currently working with asp.net mvc 5 and running into an issue. When attempting to retrieve an object by its id, it keeps returning undefined. The strange thing is that the objects display fine when checking console.log(this.vtypes). ...

I require the JSON data to be displayed in an array format

I am looking to convert a JSON object into a JSON array in Laravel. Currently, I am receiving JSON data in object format. $category = new Categories; return Response::json(array( 'error' => false, 'category' => $category- ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...

How can I properly send a file to express-fileupload using a post request in Angular 9?

I have successfully accomplished this task in Postman by following this link: https://i.sstatic.net/dKs8b.png However, when attempting to do the same in Angular, the functionality does not seem to be working. Below is the Angular code snippet: <input ...

What steps can I take to ensure an animation plays every time I click on a div featuring the animation?

As a novice in Angular, I am currently working on developing a simple application for a gym system with managers and trainers. Each gym has a list of trainers, and when I click on a trainer, their information (such as name, surname, and phone number) is di ...

The focus of the stacked ng bootstrap modal is lost

I implemented a ng bootstrap modal with an angular-calendar nested inside (https://github.com/mattlewis92/angular-calendar#getting-started) like the following: https://i.sstatic.net/vHRJl.png After opening a secondary modal by clicking on a day with a ba ...

What is the reason behind TypeScript recommending the use of the style property for the output of document.getElementById() and not for document.querySelector()?

Whenever I type "document.querySelector()." and press CTRL+Spacebar for suggestions, the 'style' property does not show up. However, it works perfectly fine with document.getElementById(). What could be causing this issue and how can I resolve i ...

Securing components in Angular2 with login verification

After wrapping multiple components' ngInit with a check to verify if users are logged in or not, I am looking for a way to avoid repeating the same code. export class ComponentX implements OnInit { constructor(private _authService: AuthService) { ...

What steps can I take to restrict a certain character from being inputted into a text field when using Angular's template-driven forms

As I work with angular template-driven forms, a peculiar issue arises when handling the dot character input by users. Rather than allowing it to be added normally to the input field, my goal is to capture the event and switch focus to a different text inpu ...

Guide to integrating a third-party library with Angular 4 for service implementation

I've been attempting to integrate collect.js into my Angular 4 project developed with the Angular CLI. Although I have imported the package using the following code snippet, I am struggling to understand how to utilize it effectively: import * as Col ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

Can an object be formed using the keys of another object, despite having different data types for the values?

Looking to dynamically generate textures based on a config object? I have a function that does just that by returning an object with the same property names but different values: function generateTextures(config: { default?: boolean, multiply?: bo ...