Frontend Angular Posting Data to Server

https://i.sstatic.net/6dcPt.png https://i.sstatic.net/uFMuL.png I have two components - one is a form and the other is a dialog with a form. When I click on the dialog with the form and input data, I want to save it first in an in-memory, and then post all my input from the dialog with the form to the backend. How can I achieve this?

This is what I did to save the form in the in-memory (calling the generate URL which is 'api/users'):

save(){
this.http.post(this.appsetting.baseURL + 'users', this.serialForm.value).subscribe((res) => {
console.log(res)
})

Here's how my in-memory looks like:

import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
@Injectable({
  providedIn: 'root'
})
export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const users = [ 
      { id: 11, itemCode: 'ICT000000211', qtyReceived:0, inputs:[{
        deliveryId: 0,
        serialNum:'string'
      }] },
    ];
    console.log(users)
    return { users : users };
  }
}

After saving, I want to post all my in-memory to my real backend using this code:

PostAll(){
return this.http.post(this.appsetting.baseURL + 'RealBackEnd/PostItem', data)
}

Answer №1

Create a centralized service to store data in an array.

When filling out a dialog form, save the current form values by clicking on 'save' and pass them to the main service.

Assume you have an array called 'users' containing all user data stored in memory:

users:any[]

In the above object, you have all the data stored in memory. When saving, perform the following:

PostAll(){
users.forEach(element=>{
 this.http.post(this.appsetting.baseURL + 'RealBackEnd/PostItem', element)
}
}

Similarly, you can use the following method:

save(){
//global variable
users.push(this.serialForm.value)
this.http.post(this.appsetting.baseURL + 'users', this.serialForm.value).subscribe((res) => {
console.log(res)
})

This approach will help you achieve your goal efficiently.

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

Using the routing module to redirect traffic

I've implemented a login page that redirects to a dashboard upon successful login. The dashboard also contains child pages. My requirement is that when a user is logged in and clicks on the logo, they should be redirected to the dashboard. If not logg ...

What is the function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

Utilizing a single code base for both Web development with Angular 4 and Mobile app development with Ionic 3

I'm interested in finding out if I can utilize the same code base for both my Angular 4 web application and an Ionic 3 mobile application that I need to develop. As someone who is new to Ionic 3, I've been exploring the documentation and discove ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

Efficiently managing various, yet closely related routes in Angular

Is it possible to have the following link item be active for multiple links? <li class="nav-item"> <a class="nav-link" routerLinkActive="active" [routerLink]="['/testGame/list']"><i class="icon-game-controller"></i&g ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...

What is the best way to verify observables during the ngOnInit phase of the component lifecycle?

Despite reading numerous articles on testing observables, such as learning how to write marble tests, I am still struggling to find a clear solution for testing a simple observable in the ngOnInit lifecycle of my component. ngOnInit(): void { this.sele ...

The application component seems to be stuck in a loading state and is not appearing as expected on my index.html

Click here to view the Plunkr <html> <head> <base href="/"> <title>Angular QuickStart</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <l ...

An error was encountered while parsing JSON data in Angular due to an unexpected token

I am currently working on implementing role-based authorization in my project. The goal is to hide certain items in the navigation bar based on the user's role. I encountered an error as shown below. How can I resolve this? service.ts roleMatch(a ...

Issue: Only one type can be named "Upload" within Apollo, Express, and Type-Graphql

I've encountered an issue while trying to execute a simple Mutation for uploading an image. The error I keep facing is: "Error: There can be only one type named 'Upload'." Here's the snippet of my code: import { FileUploadI, GraphQLUp ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

Discover the power of Angular 4 with its *ngFor loop constraints, and enhance user interaction

<ul> <li *ngFor="let hero of heroes | slice:0:10;"> {{ hero.name }} </li> </ul> <p *ngIf="heroes.length > 10" (click)="showMore()">show more 10</p> I am looking to display additional hero names when clic ...

Creating several light beams from a rotated structure

My current challenge involves shooting multiple rays from a rotating mesh in various directions targeting points on a circle divided by the number of rays. To assist with debugging, I have added ArrowHelpers for each ray with a goal for the arrows to turn ...

Optimizing performance in React: A guide to utilizing the Context and useCallback API in child

Utilizing the Context API, I am fetching categories from an API to be used across multiple components. Given this requirement, it makes sense to leverage context for managing this data. In one of the child components, the categories can be expanded using ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

Can Angular routing be used with a LAMP server?

I have decided to host my Angular 2 application on which offers a traditional LAMP stack for hosting. In my local ng serve environment, the route www.mysite.com/myapp/item/:id functions perfectly. However, when trying to access www.mysite.com/my-app/ite ...

"Encountering a Cypress Angular error: CypressError with the message 'Timed out retrying: Expected content was not

During my Cypress test run, I encountered an error message on the last step (click) which stated: Timed out retrying: Expected to find element: .button-darkblue, but never found it. Here is the code snippet: describe('Test Login', () => { i ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

How to successfully extract and understand JSON data in Angular that has been delivered from a Spring controller

I am facing a unique challenge while trying to utilize JSON data obtained from a Spring API to populate a list in Angular. Within the datasets-list.component.ts file, I have the following code: import { Component, OnInit } from '@angular/core'; i ...