A guide on capturing the response in the POST method within Angular 7

I'm currently working with Angular 7 and I need a way to know if the data has been successfully saved or not.

Within my web service code, I have designated "Success" as the status when data is saved correctly, and "Unsuccessful" if the data is not saved in the Database.

I'd like to alert the UI based on the message sent by the web service.

Below is a snippet of my UI code that calls the web service to save the data into the database:

return this.httpService.post(this.baseUrl + this.serviceUrl + 'saveData', body, httpOptions)
            .pipe(
                catchError(this.handleError('addData', data))
            );

Could someone assist me with this matter?

Thank you in advance!

Answer №1

In my experience, I have developed a straightforward method to capture and display the response from a service in a modal dialog using material design for a reusable component. Below are some pseudo code pointers that can be updated as needed:

this.backEndService.myAPI(serviceRequest)
            .subscribe(res => {
                this.postProcess(res as string);
            },
                (error) => {
                    //handle error
                }
            );

Additional logic for handling the response:

 private postProcess(generatedResponse: string) {
        //perform tasks like setting loading to false etc..
        const dialogRef = this.dialog.open(ModalDialogComponent, {
            data: generatedResponse
        });
        dialogRef.afterClosed().subscribe(result => {
            // nothing in my case
        });
    }

modal-dialog.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

@Component({
    selector: ...,
    templateUrl: ..,
    styleUrls: [...]
})


export class ModalDialogComponent implements OnInit {

    constructor(
        public dialogRef: MatDialogRef<ModalDialogComponent >,
        @Inject(MAT_DIALOG_DATA) public generatedResponse: string) { }

    ngOnInit() {
    }


    public onOk() {
        console.log('onOk');
        this.dialogRef.close({
            data: {
                closed: true
            }
        });
    }
}

modal-dialog.component.html

<h2 mat-dialog-title>....</h2>

<mat-dialog-content>
    <section fxLayout="row wrap" fxLayoutAlign="center center">
        <mat-card fxFlex="500px" fxFlex.xs="100%">
            <mat-card-title>Title
            </mat-card-title>
            <mat-card-content>
                <div fxLayout="column wrap" fxLayoutGap="40px grid">

                    <div fxLayout="row wrap" fxLayoutAlign="center center">
                        <div fxFlex="65%"><strong>Status</strong>{{generatedResponse}}
                        </div>
                    </div>

                </div>
            </mat-card-content>
        </mat-card>
    </section>

</mat-dialog-content>

<mat-dialog-actions>
    <button class="mat-raised-button" (click)="onOk()">OK</button>
</mat-dialog-actions>

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 displays [object Object] upon return

I have been struggling to send a post request, but unfortunately the API is returning undefined. When I try to send it to my API, it shows up as [object Object] getAccouting():Observable<any>{ // let json = this.http.get<any>('/assets/ ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

NavigatedRoute and Auth-protect - problem retrieving ID from paramMap

Currently working on a website for my exam project, but encountering an issue with the AuthGuard not returning the correct ID in my code. event-details.component.ts getEvent(): void { const id = +this.route.snapshot.paramMap.get('id'); ...

What steps are necessary to ensure that the extended attribute becomes mandatory?

Utilizing Express, I have set specific fields on the request object to leverage a TypeScript feature. To achieve this, I created a custom interface that extends Express's Request and includes the additional fields. These fields are initialized at the ...

Switching over to Typescript: Sending mapped properties

I'm having trouble converting my React.JS script to TypeScript. I need assistance in creating a drop-down navigation bar on my website. Here's a snippet from my Header.tsx file: The error message Property 'onClick' does not exist on t ...

Is there a way to view Deno's transpiled JavaScript code while coding in TypeScript?

As I dive into Typescript with Deno, I am curious about how to view the JavaScript result. Are there any command line options that I may have overlooked in the documentation? P.S. I understand that Deno does not require a compilation step, but ultimately ...

Retrieve the implementation of an interface method directly from the constructor of the class that implements it

I am looking to create a function that takes a string and another function as arguments and returns a string: interface Foo { ConditionalColor(color: string, condition: (arg: any) => boolean): string; } I attempted to pass the ConditionalColor metho ...

How can you make an IonPopover dynamically appear from a button with the perfect positioning?

I want to display a popover below a button when the button is clicked, similar to the example on the Ion docs page. However, I am having trouble implementing this in React as the code provided is only for Angular. Here is my current code: ... <IonButt ...

Tips for accessing a web service using only an HTML file

I am a newcomer to web services and I am working on creating a simple REST web service in Java for a basic login application. Here is the code: Server side: package com.testingws.webservices; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax ...

Unable to define an object within the *ngFor loop in Angular

In order to iterate through custom controls, I am using the following code. These controls require certain information such as index and position in the structure, so I am passing a config object to keep everything organized. <div *ngFor="let thing of ...

Executing cypress tests with tags in nrwl nx workspace: A simple guide

Currently, I am working within a nrwl nx workspace where I have set up a cypress BDD cucumber project. My goal is to run cypress tests based on tags using nrwl. In the past, I would typically use the "cypress-tags" command to achieve this. For example: &q ...

Issue with retrieving JSON objects in Next.js

I've been developing a straightforward crypto price tracker using the coingecko API. At the moment, my code is unable to retrieve any of the JSON objects from the API link, and curiously, no errors or warnings are being generated to indicate what the ...

Is there an option for keyPrefix in i18next?

For my current project, I am utilizing both i18next and react-i18next. One useful feature of using the useTranslation hook from react-i18next is the "keyPrefix" option, which helps in reducing code duplication. However, there are instances where I need to ...

Explore the world of data manipulation in Angular by experimenting with different

Embarking on a fresh Angular 2 project centered around Photos and Users. The backend work is all done, with the API in place. I've already constructed those classes. Now, I find myself pondering... To manipulate these objects on the client end, wo ...

Employing Class Categories in Static Procedures

I am currently working on developing a foundational Model that will serve as the base for a specific model class, which will have an interface detailing its attributes. Within the base Model class, I am aiming to incorporate a static factory() function th ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

Issue: "Exported functions in a 'use server' file must be async"

I'm currently working on implementing layout.tsx in the app directory of Next.js 13 to create a navigation layout that appears on all pages. I've successfully configured it so that the navbar updates when a user logs out or signs in, but there&ap ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...