Implement the async pipe and observable to handle the entire block efficiently

My API returns a large object to my Observable, and I need to showcase these values in my template.

When dealing with other data that is returned as an array, I can easily utilize the following code:

<div *ngFor="let value of values | async">
  <p>{{ value.prop }}</p>
</div>

I do not have to wait for the async operation to complete within the *ngFor, since it already has an async pipe in the parent element.

However, when it comes to working with my object, I am searching for a similar solution. Currently, I am using something like this:

<h2>{{ (obj | async)?.title }}</h2>
<p>{{ (obj | async)?.prop.prop2 }}</p>
<p>{{ (obj | async)?.another.prop }}</p>

This results in a lot of duplicated code. Is there a more concise way to achieve this?

<div *using="obj | async">
  <!-- obj has resolved, can access obj.prop -->
</div>

Answer №1

Remember to utilize the 'as' syntax when working with observables.

Keep in mind that each async pipe creates a new subscription, leading to multiple HTTP calls if your subscription involves HTTP requests. To avoid this, consider using RxJS share() so you can reuse the same observable multiple times in your template with the async pipe.

 @Component({
   selector: 'my-app',
   template: `
     <div>
       <div *ngIf="obj$ | async as obj; else empty">
      {{obj.x}}
      {{obj.y}}
      </div>
      <ng-template #empty>Empty. Please wait 5 seconds...</ng-template>
     </div>
   `,
 })
 export class App {
   s = new Subject();
   obj$;
   constructor() {
     this.obj$ = this.s.asObservable();
     setTimeout(() => {
       this.s.next({x:12, y:100});
     }, 5000)
   }
 }

Answer №2

One way to simplify your code is by creating an alias:

<div *ngIf="(data$ | async) as data">
  <h4>{{ data?.name }}</h4>
  <p>{{ data?.details.description }}</p>
  <p>{{ data?.moreInfo.info }}</p>
</div>

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

The data source retrieved through the "get" API method is missing from the mat-table

Recently, I've started working with angularCLI and I'm facing an issue in creating a table where the dataSource is fetched from a fake API. Let me share my component class: import { Component, OnInit } from '@angular/core'; import { Fo ...

What is the purpose of using @ViewChild to access a component's function from another component?

During a discussion with my tutor, I learned that in Angular we can utilize functions defined in any service by simply importing the service. However, unlike services, components cannot be directly imported into other components. To access a function from ...

Error in Angular Typescript: Utilize the return value of "filter" function to fix the issue

Encountering a sonar error: The return value of "filter" should be utilized Despite using the filter, the error persists. What might be the issue here? array.filter(item => { item.value.split(' ').forEach( i => { if ( doSomething(i) ...

Is there a way to show a mat-icon in a disabled state?

In my Angular project, I am working on implementing a mat-accordion component that consists of multiple panels. These panels can either be enabled or disabled, and I am using material-ui icons to visually represent their status. For an enabled panel, the c ...

Enhance Button functionality in Mantine TypeScript with props

I am looking to implement a feature where a button changes its background color based on the current page or path within my application. My approach involves adding a new prop (e.g., selected) to the Button component in Mantine using TypeScript. To achie ...

Do other effects promptly process actions dispatched by one ngrx Effects effect?

I am facing an issue in my Angular (2) application where I have implemented four ngrx actions: START This action is not processed by the reducer, meaning there is no state change The ngrx Effect triggers an asynchronous task and maps it to either SUCCE ...

What is the correct way to send a GET request in angular?

Trying to make a GET request from Angular to Spring Java, but encountering error code 415 zone.js:3243 GET http://localhost:8080/user/friend/1 415 Below is my Spring Java code for the endpoint: @RequestMapping( value = "/friend/{idUser}", ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

Tips for enhancing a table with extra functionality in Angular 6

Hi there! I've created a table using Angular 6 and now I'm looking to enhance it with some extra functionality: Implement an overall table search feature Allow users to sort the table by columns Add a "Page x of n" option for pagination I woul ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

Implementing enums in generic structures for routing

I am working on defining an enum that contains a list of routes. enum ServerRoutes { WHISPER_SECRET = 0, SHOUT_SECRET = 1, SHOUT_SECRET_MULTIPLE_TIMES = 2 } My goal is to develop a ServerRouter that ensures all routes are handled at compile-time. I ...

The "void" type cannot be assigned to the type "ObservableInput<{}>"

I recently encountered this issue after updating to TS 2.2.2, and I suspect that is the root cause... While the code still functions properly, I am now seeing this error. I attempted various solutions such as returning an empty observable, catching the re- ...

Ways to implement the React.FC<props> type with flexibility for children as either a React node or a function

I'm working on a sample component that has specific requirements. import React, { FC, ReactNode, useMemo } from "react"; import PropTypes from "prop-types"; type Props = { children: ((x: number) => ReactNode) | ReactNode; }; const Comp: FC< ...

Error Arises When Making Selection in PrimeNG's P-ListBox Component

Whenever I choose an item from my listbox module, I encounter an error where the value is being returned as an object instead of an array in my listbox.js file from p-listbox by PrimeNG. HTML: <p-listbox formControlName="programType" [options]="phoneT ...

Utilizing UI-GRID to showcase JSON information

I am currently in the process of fetching data from the server. [ { id:1, name:demo, request: { id: 1, localCompany: { id: 1 } } }] [{ }, { }] This is how my JSON object appears to be structured. After calling ...

Angular experiencing timeout due to Spring Boot service offline

When my Angular frontend tries to make a POST http request but the Spring Boot backend service is not running, I see the following error in the Chrome console after a few seconds: POST https://localhost:8080/report/data net::ERR_TIMED_OUT I added an erro ...

Improving mat-expansion-panel ngFor in AngularEnhancing the performance of mat-exp

I'm currently working on populating a mat-accordion with mat-expansion-panels using the code below: <mat-accordion> <mat-expansion-panel *ngFor="let item of items; trackBy: trackByFunction; let i = index" hideToggle="tr ...

Is it possible to create a nested object inside of an array?

Looking to accomplish the following: let listOne: any = ['item1', 'item2', 'item3']; let details: any; // Previously, I had a loop running and 'row' was the response outputting items // in the listOne array const ...

Charging for Firebase together with Server-Side Rendering

Utilizing a simplistic Cloud Function to ascertain whether the incoming request is bot-generated, I then deliver server-rendered content if that criterion is met on an Angular application hosted via Firebase. My understanding leads me to believe that this ...

How to add Bootstrap and Font Awesome to your Angular project

After attempting to add Bootstrap and Font Awesome to my Angular application, I am encountering issues. I utilized the command npm install --save bootstrap font-awesome and included both libraries in the angular.json file as follows: "styles": ...