Guide on displaying the length of an observable array in an Angular 2 template

I am working with an observable of type 'ICase' which retrieves data from a JSON file through a method in the service file. The template-service.ts file contains the following code:

 private _caseUrl = 'api/cases.json';
getCases(): Observable<ICase[]> 
    {    
            return this._http.get(this._caseUrl)
            .map((response: Response) => <ICase[]> response.json())
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);     
    }

In the template component, I am trying to display the length of the observable array. Despite attempting to use the async pipe and the .length operator, I have not been successful in displaying it on the DOM. The template.component.ts file includes the following code:

  ngOnInit(): void
{
    console.log("---In OnInit---");
    this._templateService.getCases()
    .subscribe(cases => this.cases = cases, error=> this.errorMessage = <any>error);
     console.log('Num of cases: ' + this._templateService.getCases().map.length);
}

The provided HTML showcases the display of observable elements while keeping specific data hidden for privacy purposes. Red circles highlight the areas where I am attempting to show the length of the observables. Browser Image

Answer №1

If you want to enhance your code, consider utilizing the async pipe. Here's an example:

// within template.component.ts
  data$:Observable<ICase[]>;
  ngOnInit() {
    this.data$ = this._templateService.getCases();
}

// in template.component.html
<ng-container *ngIf="data$ | async as data">
   {{data.length}}
   <table>
      <tbody>
        <tr *ngFor="let item of data">
            {{item}}
         </tr>
      </tbody>
   </table>
</ng-container>

Keep in mind that error handling is not included in this approach.

(I haven't tested it yet but it should function properly :D )

Answer №2

When working with observables, it is essential to subscribe to them in order to start fetching any data. Until you do so, it's merely a description of what should be done with the data.

Here's an approach: Utilize .do to attach a hook to the observable that can access the data.

ngOnInit(): void {
  this._templateService.getCases()
    .do((cases) => {
      console.log("Number of cases:", cases.length);
    })
    .subscribe(cases => { this.cases = cases; },
               error => { this.errorMessage = error as any; }
    );
}

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

json array: Tips for adding elements to a new array

In order to achieve my goal, I am looking to create a JSON array structure similar to the one shown below: var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; How can I modify the code snippet provided below to generat ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Steps for Adding a JS file to Ionic 3

I'm trying to figure out how to access a variable from an external JS file that I included in the assets/data folder. Here's what I've attempted: I placed test.js in the assets/data folder. In test.js, I added a variable testvar = "hello ...

Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet: enum Status { SUCCESS = 'success', FAILED = 'fa ...

A guide on incorporating a single class object of type Observable<any> into HTML

I'm currently working with Angular4 and have a Windows Timer subscribed observable in my typescript file. this.dynamicTime = new Observable<string>((observer: Subscriber<string>) => { setInterval(() => observer.next(this ...

Importing JSON data was unsuccessful with mongoimport

After following the steps outlined in an article about importing JSON into MongoDB (link: ), I attempted to import a file named breedData.json. The command was entered in the terminal from the root folder of my application, where the breedData.json file is ...

Combining Typescript Declarations for Express Request Object with Passport.js User/Session Integration

In my express/nodejs app, I am encountering issues with properties on the request.user object even after implementing Declaration Merging for authentication using passportjs middleware. To address this, I created a file at /types/index.d.ts in the project ...

What is the best way to add a dictionary to a JSON file without compromising the integrity of the JSON structure?

Before I explain my issue, I want to clarify that this is not a duplicated problem; it is unique. I am trying to add data to a dictionary within a JSON file using the code below. Please note that items like k['Process'] are sourced from another ...

Locate the minimum and maximum values between two inputted dates

I'm looking for a solution that provides strongly typed code. The problem arises when trying to implement solutions from a related question - Min/Max of dates in an array? - as it results in an error. TS2345: Argument of type 'Date' is not ...

Having difficulty adjusting the size of the ng-image-slider

I am facing some challenges in reducing the size of my video images. I have tried using the following link: https://stackblitz.com/edit/angular-jgtecl?file=src%2Fapp%2Fapp.component.html, as well as this slider: https://github.com/sanjayV/ng-image-slider ...

Unsteady movement of Three JS OrbitControls during rotation

Currently, I am working on a scene with three.js and using orbit controls to rotate the camera around the scene. Occasionally, while rotating, the camera starts moving erratically before calming down and rotating smoothly again. I have read about orbit co ...

Is it possible to retrieve the signature for every method within a class?

Let's consider a scenario where we have a class defined as follows: class Actions { static FooAction = 'foo' as const; someAction1() { return { type: Actions.FooAction, payload: {a: 1, b:2} }} static BarAction = &apos ...

Why does the property of {{hero.name}} function properly in a <h> tag but not in an <img> tag?

Within this template, the code below functions correctly: <h3>{{hero.name}}</h3> It also works for: <a routerLink="/details/{{hero.id}}">{{hero.name}}</a> However, there seems to be an issue with the following image path ...

Utilize only the necessary components from firebase-admin in Cloud Functions with Typescript

When I looked at my transpiled code from cloud functions, I noticed the following TypeScript import: import { auth, firestore } from 'firebase-admin'; It gets transpiled to: const firebase_admin_1 = require("firebase-admin"); Upon further exa ...

The beforePopState event in next/router is not triggering as expected

Noticing an issue where the beforePopState event is not triggering when I use the back button. This code snippet is part of a hook defined in _app.js according to the documentation. The current version being used is 12.1.5 If anyone has insights on what ...

Enable the use of unfamiliar techniques on object

I am facing a challenge with an object that contains multiple method names which are not known at compile time. The signature of these methods always remains the same, but I am unsure about how to handle this scenario. I attempted to utilize an index type ...

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

Having difficulty transforming the JSON data into the necessary format for Google Charts using JavaScript

The JSON data returned by the following controller is structured as shown below: [ {"classification":"CON","count":2}, {"classification":"PUB","count":1}, {"classification":"SENS","count":1} ] However, Google Charts requires the data to be in the followi ...

Explore an asynchronous PipeTransform experiment

Situation I have created a simple PipeTransform with an asynchronous twist. Why? Well, I have developed my own i18n service to handle parsing, pluralization, and other complexities, which returns a Promise<string>: @Pipe({ name: "i18n", pur ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...