繁体   English   中英

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

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

我有一个谷歌地图方向服务,我正在尝试将其转换为 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 类型来解决它。 我只是用了“任何”。 在你的情况下,试试

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

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

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

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

请注意,为了返回具有返回Observable<R>一个参数类型T的回调,它需要两种类型。

用法

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM