Contrasting the .toPromise() synchronous method with the pipe asynchronous method

Exploring the contrast between .toPromise().then() async approach and pipe async approach

Currently, I am utilizing the toPromise().then() method for making a synchronous call

deleteErrorList(errordetails) {
        return this.http.post(this.apiUrl + 'RemoveErrorList', errordetails, this.requestOptions)
            .toPromise().then((res: Response) => {
                return res.json();
            })
            .catch(error => {
                return Observable.throw(error);
            });
    }

HTML -

*ngFor="let variantLabel of elementData.elementDataCollection"


However, a colleague suggested using map() and asyncpipe pattern for handling observables instead of toPromise().

Consequently, I have updated my code to include .map() instead of toPromise() like so

deleteErrorList(errordetails) {
            return this.http.post(this.apiUrl + 'RemoveErrorList', errordetails, this.requestOptions)
                .map((res: Response) => {
                    return res.json();
                })
                .catch(error => {
                    return Observable.throw(error);
                });
        }

HTML -

*ngFor="let variantLabel of elementData.elementDataCollection | async"


It seems like the code functions in a similar manner for sync calls. But what exactly sets them apart? Does it solely serve as a means to handle Observable? And which approach is preferable?

Answer №1

By utilizing the ChangeDetectionStrategy.OnPush setting, the | async pipe triggers a call to ChangeDetectorRef.markForCheck() on the parent component, thereby ensuring that changes to this specific component are included in the next update cycle of change detection.

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

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...

Is there a way to modify just the homepage url of the logo on a WordPress website using the OceanWP theme?

My website, abc.com, is set up with Angular for the homepage and WordPress for the blogs. The WordPress site is located in a subfolder within abc.com. You can see the file structure in the image below. I am now looking to change only the homepage link on ...

How can I activate a function in one Angular 2 component from another?

I am working with two components named componentA and componentB. They are both siblings and children of componentMother. My goal is to have a button click on componentA trigger a function call on componentB. Would the best approach be using a service wi ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

The production build was unsuccessful due to issues with pdfmake during the ng build

Currently, I am working on an Angular 6.1.4 project using pdfmake 0.1.63 (also tested with version 0.1.66). While running ng build --prod command, I have encountered the following issue: ERROR in ./node_modules/pdfmake/build/pdfmake.js ...

Deactivate multiple input fields by utilizing various radio buttons

I need help with enabling and disabling input fields based on radio button selection. When the first radio button is selected, I want to disable three input fields, when the second is selected, only two specific input fields should be enabled (SHIFT START ...

Navigating in Angular: How can I direct to a completely new page instead of injecting it into <router-outlet></router-outlet>?

I am in the process of designing a new HTML page that requires a unique header compared to my other pages. Typically, I have been using <router-outlet></router-outlet> to inject content, resulting in consistent headers and footers across all ...

angular pipe and tap methods fail to execute the designated function

I am encountering a problem when calling a function in my login service. I have tried using a pipe and tap. Interestingly, when I use res => console.log(res), it outputs the desired result. However, when I attempt to call a function, it seems that the ...

Having trouble getting my .Net Core Application to connect with SQL Server in a Docker Container

Currently delving into Chapter 4 of the enlightening "Essential Angular for ASP.Net Core MVC" written by Adam Freeman. My focus is on executing the initial DB to operate against SQL Server in a Docker Container. Here is the original docker-compose.yml fil ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

Tips for effectively sharing custom validators across different modules

After creating a password validator based on a tutorial, I attempted to use it on multiple forms within different parts of my application. However, I encountered an error stating: Type PasswordValidator is part of the declarations of 2 modules: SignupMod ...

Tips for utilizing buttons with the antd framework in Visual Studio Code

When using the Button and Input components from antd in vscode, I encountered an error specifically with the Button component and I am curious to understand why it is happening. Interestingly, when I tried using the Input component, it did not show any er ...

Navigating a SwipeableDrawer in React with scrolling functionality

I'm currently using a swipeable drawer in React from MUI to display lengthy content. My goal is to keep the title visible even when the drawer is closed, and I was able to achieve this through the following method: MUI SwipeableDrawer I've provi ...

Creating a loading screen in Angular2: Step-by-step guide

How can you best integrate a preloader in Angular 2? ...

Have you encountered an issue while trying to retrieve CSV data using Angular HttpClient? It seems like there might be an unexpected

My Java webservice reads CSV data that my application interacts with. However, when the data is being read, I encounter the following error: SyntaxError: Unexpected token I in JSON at position 0 at JSON.parse (<anonymous>) at XML ...

Preventing Page Refresh when Button is Clicked in Angular

How can I prevent page reload when a button is clicked in Angular? I'm developing a quiz application in Angular where I fetch random questions and options from an API. When users select an option, the next question should appear without reloading the ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

What is the process for utilizing a user AD account with SecretClient in a node/TypeScript environment?

Currently, I am faced with authentication challenges while attempting to utilize the Azure Key Vault Secret client library (https://www.npmjs.com/package/@azure/keyvault-secrets). Most of the examples provided involve service principal usage, but my requ ...

Error messages are being generated by Angular CLI due to an unclosed string causing issues with the

After incorporating styles from a Bootstrap theme into my Angular 8 project and updating angular.json, I encountered a compile error displaying the following message: (7733:13) Unclosed string 7731 | } 7732 | .accordion_wrapper .panel .panel-heading ...

In order to toggle the input field's state depending on the select component's value in Angular

I have a situation with two components: a select component and an input component, as shown in the image below: https://i.sstatic.net/rjjEn.png Scenario: Currently, the input field is disabled by default. If an option is selected from the select componen ...