我该如何使用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)最佳实践是从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<[result, status]>
返回值转换为Observable<PlaceResult[]>
?
Observable.bindCallback(service.nearbySearch.bind(service))
。 - cartant