我想知道绑定(bind) promise 结果的最佳方法,即使用 Angular 2(我使用 ionic 2)注入(inject) html 标签... 如您所知,异步编码的主要问题是丢失对当前对象的引用。看来我应该将当前对象作为参数传递给 Promise 函数生成器。 我在互联网上搜索更好的解决方案,但没有找到!那么有没有更好的方法呢?
Ionic 2 itself use observation and subscribe to do async proccess. But the major problem is that for existing functions which are not observable it couldn't work!
我的方法:
可注入(inject)类:
export class PromiseComponent {
doPromise = function (obj: any) {
return new Promise(function (resolve2) {
setTimeout(function () {
resolve2({ num: 3113, obj: obj });
}, 5000);
});
}
}
点击调用:
promiseVal = 0
doMyPromise() {
this.myPromise.doPromise(this).then(this.secondFunc);//UPDATED HERE
}
//UPDATED HERE
secondFunc = function (res) {
this.promiseVal = res.num
}
HTML:
<div>{{promiseVal}} </div>
<button (click)="doMyPromise()">Do Promise</button>
最佳答案
如果您想在组件内使用 Promise:
promiseVal = 0
doMyPromise() {
this.myPromise.doPromise().then((res) => {
this.promiseVal = res.num
});
}
我不知道您的服务背后的原因,但通常是这样的(可选):
export class PromiseComponent {
doPromise() { //This method will return a promise
return new Promise(function (resolve2) {
setTimeout(function () {
resolve2({ num: 3113, obj: obj });
}, 5000);
});
}
}
OP编辑帖子后:
您可以更改此设置:
doMyPromise() {
this.myPromise.doPromise(this).then(this.secondFunc);//UPDATED HERE
}
至
doMyPromise() {
this.myPromise.doPromise(this).then(this.secondFunc.bind(this));//UPDATED HERE
}
关于javascript - promise 结果后更新 html 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43387183/