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

Angular2 Observable,如何包装第三方ajax调用

发布时间:2020-12-17 17:50:40 所属栏目:安全 来源:网络整理
导读:我正在使用google的地方api,getPlacePredictions,这是我的输入keyup事件的代码: 我的模板: ??????????? ???????????正在搜索…… 我的课 : private autocomplete; ngAfterViewInit () { this.autocomplete = new google.maps.places.AutocompleteService(
我正在使用google的地方api,getPlacePredictions,这是我的输入keyup事件的代码:

我的模板:
???????????
???????????正在搜索……

我的课 :

private autocomplete;

        ngAfterViewInit () {
            this.autocomplete = new google.maps.places.AutocompleteService();
        }

       search(){
          this.searching = true;
          this
          .autocomplete
          .getPlacePredictions( option,( places,m )=> {
             console.log( 'onPrediction',places ); 
             this.searching = false;
          } ); 
       }

是否有任何可行的方法来包装getPlacePredictions,在rxjs observable中,以便我可以利用订阅此函数?

我最终要做的是创建一个可见和不可见的加载图标,但我无法使用google的api本身,我想如果我可以将它包装在Observable中,它会变得容易.

解决方法

您可以通过这种方式将调用包装在原始可观察对象中的getPlacePredictions方法中:

search(option) {
  return Observable.create((observer) => {
    this.autocomplete
      .getPlacePredictions( option,m )=> {
        observer.next(places);
      }); 
  });
}

然后你就可以订阅了它:

this.searching = true;
this.search(option).subscribe(places => {
  this.searching = false;
  this.places = places;
});

(编辑:李大同)

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

    推荐文章
      热点阅读