Struggling to maintain consistent updates on a child element while using the @Input property

I need to ensure that the data source in loans.component.ts is updated whenever a new loan is submitted from loan-form.component.ts.

Therefore, in loan-form.component.ts, I have the following function being called when the form is submitted:

onSubmit() {
  var config = {
    headers : {
        'Content-Type': 'application/json;charset=utf-8;'
      }
    }
    this.http
      .post(this.getHostUrl(), JSON.stringify(this.model), config).subscribe();
    this.loanAdded.emit(true);
}

Defined as

@Output() loanAdded : EventEmitter<boolean> = new EventEmitter<boolean>();

Then, in loans-component.ts, I have

@Input()
set refreshData (value: boolean) {        
    this.refresh();
}

Where

refresh() {
    console.log('refresh');
    this.getLoans().subscribe((loans) => {
        this.loans = loans;
        this.dataSource = new MatTableDataSource(loans);
        this.dataSource.sort = this.sort;
        this.changeDetectorRefs.detectChanges();
    });
}

Although it works on and off, it seems to be inconsistent.

  • In Firefox and Edge, it successfully updates on the second submit and then sporadically after that.
  • In Chrome, it consistently updates.

I have also attempted to add the following:

ngOnChanges(changes: SimpleChanges): void {
    this.refresh();
}
ngOnInit() {
    this.refresh();
}
ngAfterViewInit() {
    this.refresh();
}

I notice in the console that refresh is executed three times each time the form is submitted, but the grid does not always reflect the update...

Additionally, I have a method to delete rows and update, which functions perfectly:

removeSelectedRows() {
    this.selection.selected.forEach(item => {
        // console.log(item);
        this.http.delete(this.getHostUrl() + '/' + item.Id).subscribe();
    });
    this.ngOnChanges(null);
    this.refresh();
    this.selection = new SelectionModel<Loan>(true, []);
}

Could anyone offer guidance or insight into resolving this issue?

Answer №1

A problem arises at this point:

onSubmit() {
  var config = {
    headers: {
      'Content-Type': 'application/json;charset=utf-8;'
    }
  }
  this.http
    .post(this.getHostUrl(), JSON.stringify(this.model), config).subscribe();
  this.loanAdded.emit(true);
}

The this.http.post function operates asynchronously while this.loanAdded.emit is synchronous.

this.loanAdded.emit will execute even before receiving the response from this.http.post. To address this, place this.loanAdded.emit inside the subscribe block. Like so:

onSubmit() {
  var config = {
    headers: {
      'Content-Type': 'application/json;charset=utf-8;'
    }
  }
  this.http.post(this.getHostUrl(), JSON.stringify(this.model), config)
    .subscribe(() => this.loanAdded.emit(true));
}

By doing this, you are ensuring that the emission only happens once a response is received from the POST call. Thus, you can be confident that the data on the backend has been updated successfully.

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

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Activate OnChanges by modifying a property within the object that is bound to the data

Is there a way to make ngOnChanges() fire when a property of a data-bound object changes without needing to assign a new object to the property? // Inside the component @Input() myObj: ObjType; // Component code... The above scenario does not trigger the ...

The ng-select dropdown is experiencing issues on the user interface following an update to the newest versions of Angular 6

Recently, I made the transition of my application from Angular 5 to Angular 6. As part of the update process, I also upgraded ng-select to version 2.4.2, the latest one available on npm/GitHub. However, after the upgrade, the dropdown functionality seems ...

Angular Custom Input Form: Tailored to Your Specific Needs

Need help modifying an input field? Here's how: <input type="text" formControlName="name" placeholder="placeholder" (keypress)="function" (focus)="function" You can create a component to achieve the same functionality by using this template code: ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Dynamically modifying the display format of the Angular Material 2 DatePicker

I am currently utilizing Angular 2 Material's DatePicker component here, and I am interested in dynamically setting the display format such as YYYY-MM-DD or DD-MM-YYYY, among others. While there is a method to globally extend this by overriding the " ...

What is the expected return type in TypeScript of a function that returns a void function?

I recently received feedback during a code review suggesting that I add return type values to my functions. However, I am unsure of what return type to assign to this particular function: function mysteryTypeFunction(): mysteryType { return function() ...

Exploring the depths of nested JSON with Angular2

I'm a beginner in Angular 2 using Typescript. I am trying to figure out how to access the 'D' and 'G' elements in my JSON data using NgFor. Is there a specific way or method that I can use to achieve this? [ { "A":"B", "C" ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Upgrade your AngularJS codebase with Angular 2+ services

Attempting to adapt an Angular 2+ service for use in an AngularJS project. app/users.service.ts import { Injectable } from '@angular/core'; @Injectable() export class UsersService { private users: any = [ { id: 1, name: 'john&a ...

React Hot Toast useState is unfortunately not exported from the React library

While working on a Next.js project, I encountered an issue when trying to use react-hot-toast. When I attempted to import it into any file, I received the following error message: Error - ./node_modules/react-hot-toast/dist/index.mjs Attempted import erro ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

The Google Javascript API Photo getURL function provides a temporary URL that may not always lead to the correct photo_reference

Currently, I am integrating Google Autocomplete with Maps Javascript API into my Angular 5 application. As part of my website functionality, I fetch details about a place, including available photos. The photo URL is obtained through the getURL() method. ...

What is the best way to pass data between sibling components in Angular?

Within my Angular application, I have three sibling components that share a variable called "data". This data contains sensitive information related to API endpoints for determining discounts. Due to security concerns, passing this data through the router ...

Is there a way to ensure that fields in a sub component are validated whenever we attempt to switch the Tab using a route

Hi there, I could really use your assistance. I've done some research, but I haven't been able to find a suitable solution for my problem. I have this shared component that contains the following code which enables tab navigation through various ...