首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Angular2中使用Promises和Zones

在Angular2中使用Promises和Zones
EN

Stack Overflow用户
提问于 2015-09-25 02:56:05
回答 2查看 16.2K关注 0票数 3

我想在组件的模板中显示promise的处理结果。我试过使用zone.run,但没有用。下面是我的组件:

代码语言:javascript
复制
@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方法中,但这给出了一个错误。有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-10 03:41:20

有两个问题。首先,我从es6-promise导入了Promise,它与已有的Promise类不同。感谢Eric Martinez解决了这个问题。

第二个问题是这行代码:

代码语言:javascript
复制
this.promise.then(function(msg: string) { this.result = msg; });

这里的问题是,在function(...) {...}中,this没有引用封闭的Test对象。要解决此问题,需要使用胖箭头表示法声明函数:

代码语言:javascript
复制
this.promise.then((msg: string) => { this.result = msg; });

这只是JavaScript的另一件有趣的琐事。

票数 8
EN

Stack Overflow用户

发布于 2016-01-28 20:52:07

如果您想要使用已声明的函数:

代码语言:javascript
复制
...
this.promise.then(msg => this.doSomethig(msg));
}

doSomething(msg){
  this.msg = msg;
  //other stuff
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32768854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档