我想在组件的模板中显示promise的处理结果。我试过使用zone.run,但没有用。下面是我的组件:
@Component({ selector: 'test' })
@View({ template:
`<div class="test">
<p>Result: {{ result }}</p>
</div>`
})
export class Test {
promise: Promise<string>;
result: string;
constructor(private _zone: NgZone) {
// Process promise
this._zone.run( function() {
this.promise = new Promise(function(resolve, reject) { resolve("Hi there"); });
this.promise.then(function(msg: string) { this.result = msg; });
});
}
}当它运行时,模板不会改变。我尝试将zone.run放入then方法中,但这给出了一个错误。有什么想法吗?
发布于 2015-11-10 03:41:20
有两个问题。首先,我从es6-promise导入了Promise,它与已有的Promise类不同。感谢Eric Martinez解决了这个问题。
第二个问题是这行代码:
this.promise.then(function(msg: string) { this.result = msg; });这里的问题是,在function(...) {...}中,this没有引用封闭的Test对象。要解决此问题,需要使用胖箭头表示法声明函数:
this.promise.then((msg: string) => { this.result = msg; });这只是JavaScript的另一件有趣的琐事。
发布于 2016-01-28 20:52:07
如果您想要使用已声明的函数:
...
this.promise.then(msg => this.doSomethig(msg));
}
doSomething(msg){
this.msg = msg;
//other stuff
}https://stackoverflow.com/questions/32768854
复制相似问题