Guide to executing CRUD actions on a list observable with the help of the async pipe in Angular

Up until now, I've been used to looping through lists in my Angular apps using the ngFor directive without utilizing the async pipe. However, today I came across the async pipe and decided to give it a try.

So here's an example of a component template where I implemented it:

<ng-container *ngIf="todos$ | async as todos">
  <div *ngFor="let todo of todos">{{ todo.content }}</div>
</ng-container>

And in the sample component class:

this.todos$ = this.todoService.getAllTodos();

My current dilemma is figuring out how to perform add, edit, or delete operations on the todos$ observable.

Answer №1

To start, it's important to note that requests made by the httpClient are self-completing, meaning they cannot emit any new values after completion.

A solution to this is to utilize a separate Observable or Subject. A suitable option in this scenario would be the BehaviourSubject.

First, you establish:

this.todos$ = new BehaviourSubject(null);

It should be highlighted that the default value of todos$ is set to null. To avoid using *ngIf, you can provide an empty array as an alternative.

After the request has finished, you can emit the response:

this.todoService.getAllTodos()
  .subscribe(response => {
    this.todos$.next(response);
  });

If there comes a time when you need to modify the data, you can retrieve the current value (from the BehaviourSubject), make changes to it, and then re-emit it. For instance, adding a new item could be done like this:

this.todos$.next([newItem, ...this.todos$.value]);

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

Angular two form not recognizing ng model

Below is a form with an ngModel "user.account.emailFAKE", but when the form variable is printed, this output is shown: { "name": "fill name", "account": { "email": "email address", "confirm": "confirm email" } } Is the ngModel name being completely i ...

The Challenge of Upgrading from AngularJS 1 to Angular 2: An Adapter Solution

<html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="app.css" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script> <script src="https:/ ...

Path for WebStorm file watcher's output

I'm in the process of setting up a Typescript project in WebStorm, where I want the files to be transpiled into a dist folder. This is my current project folder structure: projectroot/src/subfolder/subfolder/index.ts What I aim for is to have the f ...

Issue encountered while attempting to dynamically load feature modules using angular-cli in conjunction with webpack

Hello, I'm currently facing some challenges while attempting to utilize angular-cli in conjunction with webpack (+productivity) for the development of my angular2 application. The issue arises when I try to lazy load modules, which functioned properly ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

What causes the InvalidValueError to appear in the 'origin' property when using Angular? Is it necessary to set either a location, placeId, or query to

I have integrated agm core into my angular10 application to display google maps. The code in component.html is as follows: <agm-map [latitude]="latitude" [longitude]="longitude"> <agm-direction *ngIf="source && ...

Utilize ngx-select-dropdown to showcase various displayKey values at once

I am currently utilizing the ngx-select-dropdown plugin with a search feature, and I am looking to specify multiple values for the displayKey property such as: firstname and lastname. Here is the configuration object I am using: dropdownconfig = { di ...

Execute different commands based on operating system using NPM conditional script for Windows and Mac

Scenario: I am currently configuring a prepublishOnly hook in NPM. This hook is designed to remove the "lib" folder, transpile the typescript source files into a new lib folder, and then execute the tests. The issue at hand: There are two individuals re ...

JavaScript: Retrieve the Number of Subscribers on the BroadcastChannel

Is there a way to check if a Broadcast channel exists and see how many subscribers it has? We have a product link, and some Chrome tabs are subscribed to a Broadcast channel. We want to determine the number of listeners. const bc = new window.BroadcastCha ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Encountering a Windows 11 issue: npm ERR! errno -4058 with ENOENT bash code

Encountered a troublesome NPM issue suddenly, after taking a brief break from working on my project. Facing the following error with core-js. npm ERR! code ENOENT npm ERR! syscall spawn bash npm ERR! path C:\Users\User1\Documents\projec ...

Updating the array in React state does not work properly

Update: Visit the Snack Expo for the latest version. I have a page that displays a list. When I click on a Delete button, my goal is to remove the item with a specific id from the list. The code snippet is shown below: import { useState, memo, useCallbac ...

Navigating with Angular: The URL for the home page should be set as http://localhost:4200/

I recently implemented URL routing in my project, but I have encountered an issue. Upon redirecting to the home page, the URL changes to http://localhost:4200/home. However, I would like the URL for the home page to simply be http://localhost:4200/ instea ...

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Having trouble iterating over fields of an interface in TypeScript?

I am currently facing an issue while trying to loop through the keys of an object that contains an interface. TypeScript seems to be unable to recognize the type of the key. interface Resources { food?: number water?: number wood?: number coal?: n ...

Challenges with effectively communicating between parent and child can be addressed through the use of Angular 6

My goal is to trigger an action on a parent component based on output from a child, but I am encountering the following error: The expression has changed after it was checked. Previous value: 'ngIf: [object Object]'. Current value: 'ngI ...

"Utilize Typescript to dynamically check data types during runtime and receive alerts for any potential

INTRODUCTION I am currently working with Angular 6. In Angular, typescript is utilized to allow you to specify the data type of your function's arguments: public fun1(aaa: number) { console.log(aaa); } If I attempt to call fun1 with a parameter ...

Tips for patiently waiting to receive a value from Useselector

I have been working on a basic MyPage implementation. When Mypage.tsx is initially rendered, Redux saves user information using useEffect. However, when I attempt to retrieve data with UseSelector right after that, an error message stating that the value c ...

Error message: "ngModel is not functioning properly on checkboxes that are linked to an array

I am struggling to bind a property from an array of objects to a checkbox without success. Please refer to the following Plunker: https://plnkr.co/edit/dsQQCJrQD5kfOwcsCzze An error is occurring, stating: Can't bind to 'ngModel' since it ...