如何将Observable.bindCallback()
与返回2个参数callback(results, status)
的回调一起使用?该示例位于以下google.maps.places
API:
const service = new google.maps.places.PlacesService(map);
// service.nearbySearch(request, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
我想做这样的事情:
const handleError = err=>console.error(error);
const nearbyAsObservable = Observable.bindCallback(service.nearbySearch)
nearbyAsObservable(request)
.subscribe(
(results,status)=>{
if (status!="OK") handleError(results);
callback
}
, handleError
)
但我不确定以下内容:
1)是&#34;抛出&#34;的最佳做法。来自next
处理程序的错误并在error
处理程序中捕获它,或者只调用方法handleError()
?
2)我收到Cannot read property 'nearbySearch' of undefined(…)
错误。但是当我打电话给const nearbyAsObservable = Observable.bindCallback( service.nearbySearch.bind(service) )
时,我收到了TS错误:
// const nearbyAsObservable = Observable.bindCallback(service.nearbySearch.bind(service) )
// nearbyAsObservable(request)
[ts] Supplied parameters do not match any signature of call target.
const nearbyAsObservable: () => Observable<{}>
更新看起来这个黑客会修复TS错误
const nearbyAsObservable : any = Observable.bindCallback(service.nearbySearch.bind(service) )
nearbyAsObservable(request)
.subscribe(
(results,status)=>{
if (status!="OK") handleError(results);
callback
}
, handleError
)
但next
处理程序会在我给它(result, status)=>void
3)如何将Observable从Observable<[result, status]>
转换为Observable<PlaceResult[]>
?
答案 0 :(得分:3)
答案如下:
1)根据需要将范围绑定到您的回调(请参阅注释)
2)如果绑定范围,则使用let nearbyAsObservable : any;
修复TS错误how do I use `Observable.bindCallback()` with typescript
3)在selector
中使用Observable.bindCallback()
函数将多个返回参数映射到subscribe
函数的单个响应中,并且还抛出错误。 How do I use the RXJS selector function in the Observable.bindCallback method?
let nearbyPlaces = function(position: google.maps.LatLng) : Observable<google.maps.places.PlaceResult[]> {
const service = new google.maps.places.PlacesService(map)
// 1) bind scope
const nearbySearchCallback = service.nearbySearch.bind(service)
let nearbyAsObservable : any;
// 2) type any fixes:
// [ts] Supplied parameters do not match any signature of call target.
// const nearbyAsObservable: () => Observable<{}>
nearbyAsObservable = Observable.bindCallback(
nearbySearchCallback // with bound scope
, (results, status) => { // 3) selector function
if (status != google.maps.places.PlacesServiceStatus.OK) throw {status, results};
return results
}
);
const placeRequest = {
location: position,
radius: 25,
rankBy: google.maps.places.RankBy.PROMINENCE,
}
return nearbyAsObservable(placeRequest) as Observable<google.maps.places.PlaceResult[]>
}
// usage example:
nearbyPlaces(position).subscribe(
(results:google.maps.places.PlaceResult[])=>console.log(results)
, err=>console.error(err)
)