Capable of retrieving information from an API, yet unable to display it accurately within the table structure

I'm currently working with Angular version 13.2.6 and a .NET Core API.

I have two components, PaymentdetailsView (parent) and PaymentDetailsForm (child).

Within the PaymentDetailsForm component, there is a form that, when submitted, makes a call to the API to post data to the database.

In the PaymentDetailsView component, the data is then displayed in a table.

The issue I'm facing is that I'm unable to load the view component immediately after submitting the form. The two forms are positioned side by side, and my requirement is for the adjacent table to be populated with the updated data as soon as the form is submitted.

PaymentView.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PaymentServicesService } from '../services/payment-services.service';
@Component({
  selector: 'app-payment-view',
  templateUrl: './payment-view.component.html',
  styleUrls: ['./payment-view.component.css']
})
export class PaymentViewComponent implements OnInit {

  constructor(public http: PaymentServicesService) { }

  ngOnInit(): void
  {
    this.http.getResult();
  }
  getDetails()
  {
    // used just to check if idea is working
    //on click of a button in form this method calls get request and fill the table
  }

}

PaymentDetailsForm.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
import { PaymentServicesService } from '../../services/payment-services.service';
import { PaymentViewComponent } from '../payment-view.component';
@Component({
  selector: 'app-paymentdetailsform',
  templateUrl: './paymentdetailsform.component.html',
  styleUrls: ['./paymentdetailsform.component.css']
})
export class PaymentdetailsformComponent implements OnInit {

  constructor(private http: PaymentServicesService) { }
  paymentDetailsId: number = 0;
  cardOwnerName: string = '';
  cardNumber: string = '';
  expirationDate: string = '';
  securityCode: string = '';
  details: any;

  ngOnInit(): void {
  }

  resetForm(formvalue: NgForm) {
    formvalue.reset();
  }
  submitForm(form: NgForm) {
    this.http.postForm(form).subscribe(res => {
      this.details = res;
      console.log("success");
    }
      , err => console.log(err));
    this.http.getResult();
  }
}

PaymentService.service.ts

import { HttpClientModule , HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NgForm } from '@angular/forms';
@Injectable({
  providedIn: 'root'
})
export class PaymentServicesService {

  constructor(private http: HttpClient) { }
  posturl = 'https://localhost:7272/api/PaymentDetail';
  getUrl = 'https://localhost:7272/api/PaymentDetail';
  list: any;//to store fetched data from db
   
  postForm(form: NgForm) {
     return this.http.post(this.posturl, form.value);
  }


  getResult() {
    this.http.get(this.getUrl).subscribe(res => {
      console.log("service is called");
      this.list = res;
    }, err => console.log(err));
    
  }
}

Upon initial loading, the form and view components both display data from the database. After submitting the form and posting the data to the database, the view component does not update. How can I achieve this?

Answer №1

To ensure proper handling of data in your service, it is advisable to return an Observable and refer to this helpful guide: https://angular.io/guide/http

getConfig() {
  // Now, the function returns an Observable of Config
  return this.http.get<Config>(this.configUrl);
}

In your component, remember to subscribe to this Observable, or even better, utilize the async pipe.

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

Tips for capturing a screenshot of the ESRI Map using Angular

Is there a way to capture a screenshot of the Esri map in its current state on the UI and then convert it into a PDF for download using Angular? Below is my current .ts code, but I am open to any additional suggestions. esri-map.component.html <!-- Map ...

Angular 2: Streamlining user interface connections with extensive data rows

My challenge lies in displaying a list of items stored in an array[] when the user clicks on a tab. The data set contains around 10k rows, which is quite large, and currently takes approximately 2 to 3 seconds to render on the UI after the click event. I a ...

How is it possible that there is no type error when utilizing copy with spread syntax?

When I use the map function to make a copy of an array of objects, why doesn't it throw an error when adding a new property "xxx"? This new property "xxx" is not declared in the interface. interface A{ a:number; b:string; }; let originalArray:A[] ...

Material-UI Alert: The property `onKeyboardFocus` for event handling is unrecognized and will not be applied

Here is a more detailed trace of the issue: warning.js:33 Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored. in div (created by IconMenu) in div (created by IconMenu) in IconMenu (created by DropdownMenu) in div ...

Firebase V9: Uploading and Updating Documents

I am currently working on updating messages in Firebare for a chat functionality using the method below: markConversationAsSeen(conversationId: string, email: string) { const messages = collection(this.firestore, 'messages'); const q = q ...

Troubleshooting fastify library errors related to ajv validation

Every time I try to build my TypeScript code, I encounter these errors: The following errors are showing up in my TypeScript code: 1. node_modules/@fastify/ajv-compiler/types/index.d.ts(1,10): error TS2305: Module 'ajv' has no exported member ...

Angular compodoc tool is not considering *.d.ts files

Is there a way to make compodoc include .d.ts files in the documentation generation process for my Angular project? Even though I've added all .d.ts files to tsconfig.compodoc.json as shown below: { "include": [ "src/**/*.d. ...

What could be causing the peculiar behavior I am experiencing when a child component attempts to display values from an object fetched in the parent component?

I am currently developing an Angular application and encountering a challenge when it comes to passing data from a parent component to a child component using the @Input decorator The parent component is named PatientDetailsComponent. Here is the TypeScri ...

Tips for exporting and reusing third-party types in TypeScript

I am facing a challenge with my package, which relies on a 3rd party package API for most of its functions. How can I export the types from the 3rd party package API in my own package? For instance: React uses @types/react to define its types Let's ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

How can one easily implement a countdown timer in an Ionic 3 app?

Easily create an Ionic3 timer set to 2 minutes that displays countdown like 1:59, 1:58, and finally reaches 00:00. Once the timer hits 00:00, a block of HTML content will be shown. ...

What is preventing me from generating Face3 in my ThreeJS Typescript project

Currently, I'm in the process of generating a Mesh using Face3 within a TypeScript project that utilizes Three.js. However, I've encountered a few issues along the way. const points = [ new Face3(-1, 1, -1),//c new Face3(-1, -1, 1),//b ...

Is it possible to ensure that all values from a specific type are represented in an enum collection?

I have a Prisma enum that I've defined (not in TypeScript), and I'm curious if it's possible to synchronize a TypeScript String enum with the generated Type from the Prisma Client. Here are the key details: export const GroupInvitationSta ...

Error: The term 'makeStyles' cannot be found in the '@material-ui/core' module after installing Material-ui-pickers

Can anyone help me with using the inlineDatePicker components from Material UI pickers? I found them here: After running the npm -i command, I encountered an error during compilation: Failed to compile. ./node_modules/material-ui-pickers/dist/material-u ...

Creating an object type that includes boolean values, ensuring that at least one of them is true

To ensure both AgeDivisions and EventStyles have at least one true value, I need to create a unique type for each. These are the types: type AgeDivisions = { youth: boolean; middleSchool: boolean; highSchool: boolean; college: boolean; open: bo ...

Setting up an Angular development environment without relying on the CLI framework

I've been diving into learning Angular and experimenting with demo apps, but I'm finding it difficult to get a clear understanding of how everything works and the underlying concepts. Most resources I come across emphasize using CLI for automatio ...

Having trouble accessing child directives in Angular 2 using @ContentChildren

I'm facing an issue getting nested directives from a parent directive, as @ContentChildren is not being populated. The main goal is to implement lazy-loading for images, where each image is a nested directive within the parent directive. For instan ...

Error when using Angular CLI: npm error! The call stack size has exceeded the limit

While attempting to develop an Angular app using ng new testApp -routing, I encountered the following error. Command: ng new testApp -routing Error: npm ERR! Maximum call stack size exceeded Does anyone have a possible solution for this issue? ...

Angular 6 experiencing issues with passing data into shared functions

I have developed a universal method for checking menu access in a service module named 'AuthService'. It communicates with the DataService class to retrieve relevant data. The common menu access function is supposed to be included in all componen ...

A TypeScript utility type that conditionally assigns props based on the values of other properties within the type

There is a common need to define a type object where a property key is only accepted under certain conditions. For instance, consider the scenario where a type Button object needs the following properties: type Button = { size: 'small' | &apo ...