【发布时间】:2019-10-02 17:07:25
【问题描述】:
在我的 Angular 项目中,我有两个独立的组件。
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))
}
当我的组件启动时,promise 会通过我的内容正常解决,但是如果我使用Update now! 按钮中的update 函数再次调用我的promise,在我的后端数据更新后,promise 会返回相同的结果首次致电ngOnInit()
如何使用相同的 Promise 在我的后端调用更新的数据?这可能吗?
【问题讨论】:
-
一般来说
yes你可以解决一个已解决的承诺,但在这种情况下,我不认为你正在将Observable转换为Promise,但坚持下去我会尝试出来 -
不,您无法解决已解决的承诺。这样做不会引发异常,但也不会产生任何可观察到的效果。
标签: javascript angular typescript promise