本文介绍了我如何在打字稿中使用`Observable.bindCallback()`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Google Maps Directions服务,我正在尝试将其转换为Observable模式.这是来自 https://developers.google.com/maps/的示例文档/javascript/examples/directions-simple :

I've got a google maps direction service I'm trying to convert to an Observable pattern. Here is the example from 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)
      }
    )
  }

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

Why is typescript rejecting this pattern?

推荐答案

在尝试使用bindCallback时,我只是遇到了相同的错误.我通过显式指定指向bindCallback结果的var类型来解决它.我只是用任何".根据您的情况,尝试

I just dealt with the same error while trying to use bindCallback. I got around it by explicitly specifying the type of the var pointing to the result of bindCallback. I just used "any". In your case, try

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

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

This doesn't explain why Typescript rejects it though. I'd guess it's because the type definitions for the result of bindCallback are parameterized (i.e., they're generically typed). Look at BoundCallbackObservable.d.ts to see what I mean. Notice the multiple parameterized definitions for all those overloaded "create" methods (one of which is ultimately what gets invoked).

这篇关于我如何在打字稿中使用`Observable.bindCallback()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 06:44