【问题标题】:Angular2 Observable - how to wrap a third party ajax callAngular2 Observable - 如何包装第三方 ajax 调用
【发布时间】:2016-06-04 06:17:48
【问题描述】:

我正在使用 Google 的地点 api - getPlacePredictions

这是我的 input keyup 事件的代码:

我的模板

<input type="text" (keyup)='search()'>
<div *ngIf="searching">Searching ... </div>

我的班级

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 可观察对象中,以便我可以利用订阅此函数的优势?

我最终在这里要做的是创建一个可见和不可见的加载图标,但我无法用谷歌的 api 本身正确地做到这一点,我想如果我可以将它包装在一个 Observable 中,它会变成容易。

【问题讨论】:

  • angular.io/docs/ts/latest/cookbook/…。它解释了如何在服务中使用 RxJS5 主题(它比 @Jigar 呈现的更 Angular)。将您的 Google 地图交互放入服务中,并使用 next() 发出数据。让组件订阅更改。

标签: angular rxjs observable google-places


【解决方案1】:

您可以通过这种方式将对 getPlacePredictions 方法的调用封装在原始 observable 中:

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

然后你就可以订阅它了:

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

从更高版本的 Angular 开始https://stackoverflow.com/a/55539146/13889515

用途:

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

【讨论】:

【解决方案2】:

您可以在包装第 3 方 ajax 调用的 Angular 服务中创建一个 RxJS 主题。例如:

@Injectable()
export class PredictionService {
  public Prediction: rx.Subject();
  private autocompleteService: new google.maps....
  constructor() { 
  this.Prediction = new rx.Subject();
  }

  getPredictions(options: any) {
    this.autocompleteService.getPlacesPrediction(options,(places, m)=>{
      this.Prediction.onNext(places); // pass appropriate predictions
   });        
  }    
}

然后您可以通过调用服务方法来请求数据,并通过订阅 RxJS 主题获得响应。

@Component() //configuration avoided for brevity
class Component 
{
 constructor(private PredictionService) {
 this.PredictionService.Prediction.subscribe((placesResult)=>{
   ... //This is where you get your data.
 });
  }

  search(){
   this.PredictionService.getPredictions(options);
  }
}

在订阅 Observable 的函数中,您可以切换加载图像的可见性。

【讨论】:

  • (那是波斯语吗?),请您举例说明一下。
猜你喜欢
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2012-07-23
  • 2017-03-26
相关资源
最近更新 更多