加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度 – 等待观察完成

发布时间:2020-12-17 07:11:06 所属栏目:安全 来源:网络整理
导读:我有一个方法需要等待一个observable完成.我知道observable非常适合随着时间的推移返回单个数据,但是我需要知道这个observable何时完全返回它的所有数据,所以我可以在它返回的对象上运行验证代码. getCustom方法订阅了提供的url上的可观察运行,然后返回obser
我有一个方法需要等待一个observable完成.我知道observable非常适合随着时间的推移返回单个数据,但是我需要知道这个observable何时完全返回它的所有数据,所以我可以在它返回的对象上运行验证代码.

getCustom方法订阅了提供的url上的可观察运行,然后返回observable.

我不太确定这是否是解决这种情况的最佳方式,所以如果有人能给我任何建议或方向来处理这个问题,我将不胜感激.

private validateQuoteRetrievalAnswers(reference: string) {

         // Get the risk from the server
        this.riskManager.getRiskFromServer(reference);

        if (this.riskManager.risk) {
            // Validate risk that was returned
        }
    }
getRiskFromServer(quoteReference: string) {

    this.riskService.getCustom("Url").subscribe => {
        // need to know when the observable has returned the risk
    });

}

解决方法

我将如何应对这一挑战:

查询你的后端,当我们得到我们需要的东西时,将它推送到主题

riskSubject = new Subject<Risk>();

getRiskFromServer(quoteReference: string) {
  this.riskService.getCustom("Url")
  .subscribe( 
    data => { this.riskSubject.next(data); },error => { console.log(error) }
 });
}

然后订阅主题并等到你得到你需要的东西并开始验证

private validateQuoteRetrievalAnswers(reference: string) {

         // Get the risk from the server
        this.riskManager.getRiskFromServer(reference);
        // subscribe to subject
        this.riskManager.riskSubject.subscribe(
         data => {
           //do your validation
        })
}

The heart of an observable data service is the RxJs Subject. Subjects implement both the Observer and the Observable interfaces,meaning that we can use them to both emit values and register subscriptors.

The subject is nothing more than a traditional event bus,but much more powerful as it provides all the RxJs functional operators with it. But at its heart,we simply use it to subscribe just like a regular observable

来源:angular-university.io

或者您可以使用Observable.fromPromise(promise)但如果您不熟悉ng2,这将使事情变得更复杂一些

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读