简体   繁体   中英

Calling promise resolve multiple times, returning same old results

In my angular project, I have two separate 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.getMyPromise()

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

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

  //results:
  //[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]
  //same outdated results of first call
}

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

When my component start, the promise is resolved normally with my content, but if I call my promise again using the update function in Update now! button, after my data in backend has updated, the promise return same results of first call in ngOnInit()

How can I call the updated data in my backend using this same promise? That is possible?

A promise is a one-way state machine so once it is resolved, it will stay that way forever. You cannot change that. Only when it is in the pending state can you resolve it with a value. Trying to call resolve() again on a promise that is not in the pending state just ignores the call (does nothing).

How can i call the updated data in my backend using this same promise? That is possible?

You will need to call your original asynchronous operation again:

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

to get a new promise that is tied to the new asynchronous action to get the new data. This new promise will resolve with the new data.

You always get the same result because you don't call de server again.

For your code work as you expect you need to implement more lines of code like that:

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();
}

See more about event emitter in https://dzone.com/articles/understanding-output-and-eventemitter-in-angular

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM