在 Angular2 中使用承诺和区域
Using Promises and Zones in Angular2
我想显示在组件模板中处理承诺的结果。我试过使用 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 方法中,但这给出了一个错误。有什么想法吗?
有两个问题。首先,我从 es6-promise 导入 Promise
,这与已经可用的 Promise
class 不同。感谢 Eric Martinez 解决了这个问题。
第二个问题是这行代码:
this.promise.then(function(msg: string) { this.result = msg; });
这里的问题是,在 function(...) {...}
内部,this
不引用封闭的 Test
对象。要解决此问题,需要使用粗箭头符号声明该函数:
this.promise.then((msg: string) => { this.result = msg; });
又是一篇精彩的 JavaScript 琐事。
如果您想使用已声明的函数:
...
this.promise.then(msg => this.doSomethig(msg));
}
doSomething(msg){
this.msg = msg;
//other stuff
}
我想显示在组件模板中处理承诺的结果。我试过使用 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 方法中,但这给出了一个错误。有什么想法吗?
有两个问题。首先,我从 es6-promise 导入 Promise
,这与已经可用的 Promise
class 不同。感谢 Eric Martinez 解决了这个问题。
第二个问题是这行代码:
this.promise.then(function(msg: string) { this.result = msg; });
这里的问题是,在 function(...) {...}
内部,this
不引用封闭的 Test
对象。要解决此问题,需要使用粗箭头符号声明该函数:
this.promise.then((msg: string) => { this.result = msg; });
又是一篇精彩的 JavaScript 琐事。
如果您想使用已声明的函数:
...
this.promise.then(msg => this.doSomethig(msg));
}
doSomething(msg){
this.msg = msg;
//other stuff
}