Access the value of an object field from an observable by utilizing the async pipe

I am interested in delving deeper into the use cases for the async pipe in Angular.

The concept of having data asynchronously appear in the view simply by adding a pipe that subscribes to the data is quite appealing to me.

However, I have primarily encountered and correctly applied the async pipe when dealing with network requests or custom observables that contain either an array of data or a single field (such as an observable string).

For instance:

Let's consider making an API call that retrieves an array of college students.

// The data is part of a network response
$students = ...get...map... 
[
  {
    name: "Bob OConnel",
    id: 0,
    description: "young..."
  },
  {
    name: "Rick Luckard",
    id: 3,
    description: "young..."
  },
  {
    name: "James Wing",
    id: 2,
    description: "young..."
  }
]

This can be displayed in a template as follows:

<tr *ngFor="let student of $students | async">
  <td>{{student.id}}</td>
  <td>{{student.name}}</td>
  <td>{{student.description}}</td>
</tr>

Nevertheless, sticking to the REST API approach, I haven't come across a production API call that only returns an array of data. Typically, there are additional fields at the same level as the array of data for specific reasons. Hence, I don't wish to discard these extra fields while mapping.

Therefore, instead of $students being an array, it would transform into:

// The data is in a network response
$students = ...get...map... 
{
  id: "69asdkasdkljasd6969"
  href: "someURLrepresentingTheDatasOrigins"
  length: 3
  items: [
    {
      name: "Bob OConnel",
      id: 0,
      description: "young..."
    },
    {
      name: "Rick Luckard",
      id: 3,
      description: "young..."
    },
    {
      name: "James Wing",
      id: 2,
      description: "young..."
    }
  ]
}

This implies that in the template, I can attach an async pipe to the $students observable, but not to its internal fields.

Clearly this doesn't function because the fields within the observables themselves...

{{$students.id| async}}
// or
<tr *ngFor="let student of $students.items | async">...</tr>

Hence, on network responses like this one, should I extract the values of the response into their individual observables if I aim to bind them asynchronously in a template? Is there a workaround if I prefer not to split the network response into multiple smaller objects?

It seems like I might be overlooking something obvious about how observables are utilized that could clarify this issue for me. Please let me know if my question requires further clarification.

UPDATE I discovered a feature here that I wasn't aware of:

Extremely useful for scenarios where some type of loading indicator should replace asynchronous data. It also helps consolidate subscriptions in one place. While it may vary based on personal preference, I believe in many instances, I would opt for placing the subscription within an *ngIf.

Is it possible to incorporate the same else template logic into an *ngFor..?

Answer №1

There is no need to map each value into its own observable. Instead, you can simply wrap your observable in parentheses along with the async pipe and access the fields inside the object returned by the observable.

Give this a try:

<tr *ngFor="let student of ($students | async).items">
  <td>{{student.id}}</td>
  <td>{{student.name}}</td>
  <td>{{student.description}}</td>
</tr>

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

Dealing with nested JSON structures in reqwest: A comprehensive guide

My current project involves utilizing reqwest library to execute a GET request on . Sending a request to a single-level json endpoint like is straightforward use std::collections::HashMap; fn main() { let body = reqwest::blocking::get("https://h ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

What is the method to incorporate type hints for my unique global Vue directives?

When I import or create a directive in an SFC file, I can receive TypeScript hints like this: import vFocus from 'my-custom-component-library'; View demo with ts hints However, if I globally register it in main.ts, the type hints are not availa ...

Exclude certain APIs from utilizing basic authentication in Fastify

I currently have two APIs set up: /auth and /no-auth. My goal is to only use basic authentication for one of them. To implement this, I am using the fastify-basic-auth plugin with fastify in a node environment. The /auth route should require authenticat ...

Visual Studio - Error TS1005 'Unexpected token'

After spending nearly 5 hours scouring the internet for a solution, I am still unable to resolve this persistent issue. The responses I've found so far do not seem to address the specific problem I'm facing. Although I have upgraded the tsc vers ...

The presence of a constructor in a component disrupts the connection between React and Redux in

I am facing an issue with the connect function from 'react-redux' in my Typescript class example. The error occurs at the last line and I'm struggling to understand why it's happening. The constructor is necessary for other parts of the ...

Is there a way to configure eslint to ignore a folder located outside of the root directory?

This is the layout of my project: -lib (git submodule housing a JavaScript library) -A (Vue.js + TypeScript + ESLint app that utilizes lib) -B (another module with an Express app) When running the A app, I encounter eslint errors with the lib submodule: E ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

Implementing Material Design in React using TypeScript

I'm currently in search of a method to implement react material design with typescript, but I've encountered some challenges. It appears that using export defaults may not be the best practice due to constraints in my tsconfig. Is there an al ...

Utilizing Angular/TypeScript to perform mathematical calculations within the component.ts file, it has been found that the addition operator (+) does not

In this scenario, I have chosen to utilize a different approach instead of using type="number" because users can easily remove it by pressing F12. While including type="number" in my HTML code does work, it still remains unclear why the minus sign work ...

Using Firebase Database, Angular2 employs UID (User ID) as the primary key

Creating a signup component in my app using Firebase as the authentication method and database. After registering a new user, a key is generated and all user information, including the UID from authentication, is saved in the database. I want to use the UI ...

Having difficulties establishing a connection with the websocket URL generated by Spark Java

I'm currently working on creating a websocket using the sparkjava framework. Here is the code snippet for setting up the websocket: public final class MainWS { static Map<Session, String> USER_SESSION_MAP = new ConcurrentHashMap<>(); stat ...

Is Typescript reliable when working with a reference to a DOM element?

In this scenario, a function is provided with the task of obtaining a reference to a DOM element and executing certain actions: function getElementAndDoStuff() { // element: HTMLElement | null const element = document.getElementById('id'); ...

Update the header background color of an AG-Grid when the grid is ready using TypeScript

Currently working with Angular 6. I have integrated ag-grid into a component and I am looking to modify the background color of the grid header using component CSS or through gridready columnapi/rowapi. I want to avoid inheriting and creating a custom He ...

When using ngStyle to bind a variable, the binding variable will be null

Currently, I am attempting to utilize ngStyle to set the background image. <div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }"> The fun ...

The Raycaster fails to identify objects that have been rotated

I have recently started working with Three.js and I'm facing an issue with raycasting not detecting certain parts of a rotated mesh object. For instance, in the image below, when the mouse is at the position of the green circle, it's detected as ...

Navigating with multiple parameters in Angular 7 routing

I am currently facing an issue where I need to navigate to the same component with different parameters. Although I can subscribe to the params through the ActivatedRoute, I'm encountering a problem when trying to call router.navigate within the subsc ...