我如何使用 `Observable.bindCallback()` 和打字稿

how do I use `Observable.bindCallback()` with typescript

我有一个 google 地图方向服务,我正在尝试将其转换为 Observable 模式。这是来自 https://developers.google.com/maps/documentation/javascript/examples/directions-simple 的示例:

  function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    directionsService.route({
      origin: document.getElementById('start').value,
      destination: document.getElementById('end').value,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

我尝试了以下方法:

import { Observable } from 'rxjs/Observable'; 
...
  // the callback version works
  getRoute (route: any) {
    const defaults = { 'travelMode': 'WALKING' };
    route = Object.assign(defaults, route);
    this._directionsService.route(
      route
      , (res:any, status:string) => {
          if (status == 'OK')
            this.displayRoute(res);
          else
            this.handleError(res)
       })
  }

  // the Observable version doesn't get past typescript
  getRoute$ (route: any) {
    const defaults = { 'travelMode': 'WALKING' };
    route = Object.assign(defaults, route);
    let route$ = Observable.bindCallback(
      this._directionsService.route
      , (res, status)=>{res, status}
    );
    // TS says, "Supplied parameters do not match any signature of call target
    route$( route ).subscribe(
      (resp:any)=>{
        // also, how do I throw an error from the selector func?
        if (resp.status == 'OK')
          this.displayRoute(resp.res);
        else
          this.handleError(resp.res)
      }
    )
  }

为什么打字稿拒绝这种模式?

我刚刚在尝试使用 bindCallback 时遇到了同样的错误。我通过显式指定指向 bindCallback 结果的 var 类型来绕过它。我刚用了 "any"。在你的情况下,试试

let route$ : any = Observable.bindCallback(...)

这并不能解释为什么 Typescript 会拒绝它。我猜这是因为 bindCallback 结果的类型定义是参数化的(即,它们是一般类型的)。看看 BoundCallbackObservable.d.ts 就明白我的意思了。请注意所有那些重载 "create" 方法的多个参数化定义(其中一个最终被调用)。

在 rxjs 5 中,您可以通过满足以下类型签名来解决此问题。

static create<T, R>(callbackFunc: (v1: T, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T) => Observable<R>;

请注意,需要两种类型才能 return 具有一种参数类型 T 的回调 returns Observable<R>.

用法

type routeType = String

interface returnType = {
  res: any
  status: any
}

let route$: any = Observable.bindCallback<routeType, observableType>(this._directionsService.route, (res, status)=>{res, status})

现在 route$ 的类型是 (v1: routeType) => Observable<observableType>