The Updating Issue: Angular 2 Table Fails to Reflect Value Changes

I have initialized a table with user details using the ngOnInit() method.

When I click on the "create user" button, it opens a form to add a new user to the database. However, the table does not update automatically with the new user's information. How can I achieve this?

Here is the code snippet:

import { Component, OnInit } from '@angular/core';
import { IUsermgmt } from './usermgmtinterface';
import { UsermgmtService } from './usermgmt.service';

@Component({
selector: 'um-user',
styleUrls: ['./usermgmt-list.component.css'],
templateUrl: './usermgmt-list.component.html'
})
export class UserListComponent implements OnInit{
    errorMessage: string;
    usermgmt: IUsermgmt[];

constructor(private _usermgmtService: UsermgmtService,private        userPosterService:FormPosterUser){
    }

updateTable(userData){
    this.usermgmt = userData;
    this._usermgmtService.getUserlist()
            .subscribe(
                usermgmt => {                      
                    this.usermgmt = usermgmt;
                    console.log("inside Update table function" +JSON.stringify(this.usermgmt));
                },
                 error => this.errorMessage = <any>error);
    }

 ngOnInit(): void {
       this._usermgmtService.getUserlist()
            .subscribe(
                usermgmt => this.usermgmt = usermgmt,
                 error => this.errorMessage = <any>error);
    }

} 

The line below doesn't reflect in the table this.usermgmt = userData;

Code for submitting the form is as follows:

    submitForm(form: NgForm) {
    // validate form

    this.formposteruser.postUserForm(this.model)
        .subscribe(
          data => {
            console.log('success: ', data);
            this.us.getUserlist()
                .subscribe(
                    usermgmt =>{
                          this.usermgmt = usermgmt;
                          this.userService.updateTable(this.usermgmt);         
                    },
                     error => this.errorMessage = <any>error);
          },
          err => console.log('error: ', err)
        );
  }

how do i reflect the new usermgmt data on the table?

Html code

<div class='panel panel-primary'>
<div class='panel-heading'> 
   <button class="btn btn-sucess">  <a [routerLink]="['/newuser']">Create New User</a> </button>
   <button class="btn btn-danger pull-right" (click)=onDeleteClick()>Delete User</button>
</div>

<div class='panel-body'>
    <div class='row'>
        <div class='col-md-4'>Search by UserName: </div>
        <div class='col-md-4'>
            <input type='text'
            [(ngModel)] = 'listFilter'/>
        </div>
    </div>
    <div class="nestedcomponent">
    <div class='table-responsive'>
        <table  class='table'
                    *ngIf='usermgmt && usermgmt.length'>
            <thead>
                <tr>
                    <th>{{usermgmt.length}}</th>
                    <th>User name</th>
                    <th>User Group</th>
                </tr>
            </thead>
            <tbody>
                    <tr *ngFor='let usermgmt of usermgmt | usermgmtFilter:listFilter'>
                        <td>
                             <input #{{usermgmt.emp_num}} [(ngModel)]="usermgmt.selected" type="checkbox" (change)="checkbox(usermgmt)">
                        </td>
                        <td [routerLink]="['/userEdit']" (click)="onTableSelect(usermgmt)">{{ usermgmt.user_name}}</td>
                        <td>{{ usermgmt.ug_desc|| 'Unassigned'}}</td>
                    </tr>
            </tbody>            
        </table>               
</div>


Please provide assistance. Thank you in advance.

Answer №1

To start, it is recommended to isolate your service request in a separate function like this:

fetchUserList(){
    this._usermgmtService.getUserlist()
            .subscribe(
                usermgmt => this.usermgmt = usermgmt,
                 error => this.errorMessage = <any>error);
    }
}

Then, when the submit button is clicked, ensure that you are subscribing to the web service data again by following these steps:

refreshTable(userData){
    this.usermgmt = userData;
    this._usermgmtService.getUserlist()
            .subscribe(
                usermgmt => {                      
                    this.usermgmt = usermgmt;
                    console.log("inside Update table function" +JSON.stringify(this.usermgmt));
                },
                 error => this.errorMessage = <any>error);
    this.fetchUserList();
    }

Additionally, in your ngOnInit() method, remember to call the fetchUserList() function:

ngOnInit(): void {
       this.fetchUserList();
} 

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

Unveiling the Mysteries of HTTP Headers in Angular

Seeking a way to retrieve a token set in the http header within my Angular application. This is how my Angular application is being served: var express = require('express'); var app = express(); var port = process.env.PORT || 3000; var router = ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Generate a dynamic interface using properties and options provided in a JavaScript object

Can Typescript support the following scenario: I have a structure where keys represent properties and values are arrays of options for those properties: const options = { foo: [fooOption1, fooOption2, ...], bar: [barOption1, barOption2, ...], ... } ...

The type 'any' cannot be assigned to the type 'never' as a parameter

const [files, setFiles] = useState([]) const handleChange = (event: any) => { setFiles.push(event.target.files[0].name) return (<div> {files.map((file: any) => ( <p>Hello!</p> ))} </ ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...

Unlocking the potential of deeply nested child objects

I have a recursively typed object that I want to retrieve the keys and any child keys of a specific type from. For example, I am looking to extract a union type consisting of: '/another' | '/parent' | '/child' Here is an il ...

arranging data in html table columns using angular 2

I am facing a challenge where I require each column of a table to be sorted in ascending order every time it is clicked. The sorting logic implemented is a standard JavaScript method. While this method works well in most scenarios, it encounters issues whe ...

The lazy loading feature in Angular 12 is not functioning correctly for path modules

My application has a jobs module with various components, and I'm trying to lazy load it. However, I've encountered an issue where accessing the module through the full path http://localhost:4200/job/artist doesn't work, but accessing it thr ...

Stop redux useSelector from causing unnecessary re-renders

I'm working on a component in React-Redux that utilizes the useSelector hook to retrieve a dictionary from the Redux store. This dictionary maps UUIDs to objects containing data that I need to display. interface IComponentProps { id: string } const ...

Issue with Ionic 3 subscribes triggering repeatedly

I've been struggling with the code for an Ionic taxi app for a few weeks now. My main issue is that whenever the page loads, the subscription gets triggered multiple times along with other functions within it. The same problem occurs when any travel i ...

Encountered an issue while configuring the Apollo server - The type '() => void' cannot be assigned to type '() => DataSources<object>'

I need help with a TypeScript-related issue. I am struggling to implement the expected return type for the function dataSources in this scenario. Here is the code snippet: const dataSources = () => { quizzessApi: new QuizzessDataSource(); } const ...

Setting multiple dynamic values for select inputs in reactive forms can be achieved by following these steps

I am currently developing a dynamic select feature using reactive form in my project. So far, I have successfully implemented dynamic selects with the same values. However, I now have a requirement to load the dropdown values dynamically based on certain c ...

How can I pass DOCUMENT in Angular?

In my directive, I use dependency injection to access the DOCUMENT and set up an event listener: constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit() { this.document.addEventListener('click', this.clicked, true); } @Bound ...

The specified format of `x-access-token` does not match the required type `AxiosRequestHeaders | undefined`

I am encountering an issue while trying to add an authHeader to the "Service". The error message displayed is: Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequest ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

Can a function's return type be set to match the return type of its callback function?

Check out the following function export const tryAsyncAwait = async (fn: () => any) => { try { const data = await fn(); return [data, null]; } catch (error) { return [null, error]; } }; If I use this function as an example... const ...

What causes the "Method Not Allowed" error while trying to restore the package.json package in VS2015?

When trying to restore a package.json file in VS2015, I am encountering a "Method Not Allowed" error. https://i.stack.imgur.com/OgK5P.png https://i.stack.imgur.com/AAkoQ.png The error log displays the following: npm ERR! Error: Method Not Allowed npm ER ...

Error in Node.js with MongoDB: Array of OptionalId<Document> Typescript typings

I have successfully established a connection and written to my MongoDB collection, but I am encountering a type error that is causing some confusion. Below is the code snippet along with the error message: interface Movie { id: number; title: string; ...

Informing Typescript that a variable has already been null-checked

An unusual yet structurally sound code snippet is presented below: function doFoo(food: string | null = null) { food = food ?? getFood(); // getFood: () => string | null if (!food) { throw Error("There's still no food :("); } plate[fo ...

What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language. One interesting data type I played with is enums. Here's an example of code I used: enum colors {red=1,green=0,blue,white}; console.lo ...