Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components.

parent.component.ts

mypromise = this.httpClient.get<any>('http://localhost').toPromise()

parent.component.html

<app-children #child [promise]="mypromise"></app-children>

<button (click)="child.update()">Update now!</button>

child.component.ts

@Input promise: Promise<any>

ngOnInit(){
  this.fetchPromiseData()

  //results:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]  
}

update(){
  this.fetchPromiseData()
  //expected:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}, {id: 3, text: 'new data'}]  

  //results:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]
  //still displaying outdated results from the initial call
}

fetchPromiseData(){
 this.promise
 .then(data=>console.log(data)) //here I log the results in the console
 .catch(e=>console.log(e))
}

When the component initializes, the promise resolves with the expected data. However, upon triggering the update function by clicking the Update now! button, the promise continues to return the initial results from ngOnInit(), rather than the updated data from the backend.

Is it possible to update the promise to fetch the latest data from the backend? How can I achieve this?

Answer №1

Once a promise is resolved, it remains in that state permanently, as it functions as a one-way state machine. It is not possible to alter this. Only when the promise is in the pending state can you resolve it with a value. Any attempt to call resolve() on a promise that is not in the pending state will simply be ignored.

Is it possible to fetch updated data in my backend using the same promise? How can I achieve this?

In order to retrieve updated data from your backend using the same promise, you will need to initiate the original asynchronous operation once more:

this.httpClient.get<any>('http://localhost').toPromise()

This action will result in a new promise being generated, connected to the subsequent asynchronous operation that fetches the updated data. The new promise will resolve with the fresh data retrieved from the backend.

Answer №2

Consistently obtaining the same outcome is a result of not making another server call.

To ensure your code functions as intended, additional lines of code must be implemented, such as:

parent.component.ts

public mypromise;
    ngOnInit() {
     mypromise = this.getSomethig();
    }

    public function getSomething() {
     return this.httpClient.get<any>('http://localhost').toPromise();
    }

child.component.ts

@Input() promise: Promise<any>
@Output() getSomething = new EventEmitter<any>();

ngOnInit(){
 this.promise
 .then(data=>console.log(data)) //here i log my results in console
 .catch(e=>console.log(e))

 //results:
 //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]  
}

update(){
     this.getSomething.emit();
}

Explore more about event emitter at

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

The ng build run command is encountering an issue due to the absence of Angular.json file

I attempted to update Angular CLI but encountered a major issue. Here is the Error Image. Can someone please provide guidance on how to resolve this problem? @angular-devkit/core 0.5.6 @angular-devkit/schematics 0.5.6 @angular/cli ...

Using AngularJS to handle form data without ng-model

I am facing a unique situation that may seem a bit strange. I have a form that needs to edit/update information from different objects, such as services. My goal is to use ng-model to link input fields to their respective objects, but when the form is sub ...

Analyzing string values in Cypress

When attempting to compare two values within a page and make an assertion, my goal is to retrieve the value of one text element and compare it with another value on the same page. While I find this process straightforward in Java/selenium, achieving the ...

How to create classes in typescript without utilizing the class keyword

As someone new to TypeScript, I have a curious question about classes. In pre-ES6 JavaScript, there were no classes. So, naturally, one would think it's possible to avoid using them in TypeScript as well. However, I am struggling to figure out the c ...

Bundling JSPM with an external system JS file

Currently, I am loading my Angular2 file as a System js module from a CDN. Within my project, I have multiple files importing various System js modules of Angular2. However, I am now looking to bundle my local JavaScript files using JSPM. But when I ente ...

What is the proper way to credit the glyphicons element in Twitter's bootstrap framework?

According to the section on icons in the Base CSS page of GitHub's Twitter bootstrap, Glyphicons Halflings were not originally available for free. However, thanks to an agreement between Bootstrap and the creators of Glyphicons, developers can now use ...

When a user clicks on an anchor tag, close the current window, open a new window, and pass the

I have a scenario where I have an anchor tag that triggers the opening of a window on click. In this newly opened window, there is a table with a column containing another anchor tag. Here is what I am trying to achieve: Code for the anchor tag: functio ...

Managing the React Router component as a variable

I'm currently working on integrating React-Router into an existing React app. Is there a way to use react-router to dynamically display components based on certain conditions? var displayComponent; if(this.state.displayEventComponent){ {/* ...

Issue with passing parameter in Jquery AJAX request to controller function

Currently, I am integrating a Jquery AJAX Call into my MVC Application. Here is an overview of how my view is structured: <p> Name @Html.TextBox("Name") Date @Html.TextBox("Date") <input type="submit" id="SubmitName" value="Submit" /& ...

Switch image formats to webp using react js

Utilizing the react-dropzone package, I aim to incorporate images into my application. To achieve this, I must send the images to a firebase server after managing image conversions. Whilst browsing through YouTube tutorials, I came across a guide demonstr ...

Transferring data in PDF format through email with the help of PHPMailer and html2pdf

Having trouble sending PDF or PNG files over email despite multiple attempts. Despite reading countless articles on the topic, nothing seems to be working as suggested. Can anyone provide assistance? I am using PHPMailer along with html2pdf and html2canva ...

How to smoothly glide to the bottom of a chat box by scrolling synchronously

I am currently in the process of developing a chat application. Each time a user sends a new message, it is added to a list of messages displayed in an unordered list (ul). I have successfully made the ul scrollable, but unfortunately, when a new message i ...

Are there any other methods besides @ViewChild to access template elements by template ID in Angular v4.3.3?

In the past, using @ViewChild('#templateId') was an accepted method for obtaining an Element Reference. @ViewChild('#templateId') elementName: ElementRef; However, it appears that this is no longer a viable approach as @ViewChild now ...

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

My selection of jQuery multiselect is experiencing issues with enabling disabled options

Incorporating the chosen jQuery plugin into my project has presented me with a challenge. The issue at hand is listed below. I have implemented a dropdown menu that includes both continents and countries in the same list. The specific scenario I am encou ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Transform a single data point into pixels by converting its latitude and longitude coordinates

I am facing a specific challenge where I have hit a roadblock after conducting some research. The issue at hand is this: I am working with a raster image that has known dimensions (800 x 800 px) I have two points within this image with their pixel and g ...

Customize the appearance of parent components based on the content of their child elements

I am currently working on a component that contains multiple instances, each with its own unique internal component (acting as a modal wrapper). I need to customize the size of each modal instance independently. How can I achieve this customization when th ...

Using Javascript or jQuery to Enhance the Appearance of Text on a Website

Is there a way to automatically apply styling to specific phrases on our website by searching for instances of those phrases? For example: <div> This is what you get from <span class="comp">Company Name</span>. We do all kin ...

Exploring discrepancies between two tables with the power of Javascript

const firstTable = document.getElementById('table_1') const secondTable = document.getElementById('table_2') const rows1 = firstTable.rows const rows2 = secondTable.rows for (let i = 0; i < rows1.length; i++) { for (let x in rows ...