我需要将回调方法链接到Observable链。
private testMethod(): Rx.Observable<any> {
const deferred = this.$q.defer();
let promise = deferred.promise;
this.$window.fileChooser.open((results: any) => {
deferred.resolve(results);
}, (error: any) => {
this.Logger.log(error);
});
return this.rx.Observable.fromPromise(promise)
.map((contentURI: string) => {
// need to link call-back method
this.$window.FilePath.resolveNativePath(contentURI, (absolutePath: any) => {
// need to pass absolutePath to next map method
return absolutePath;
});
})
.map((fileEntry: any) => {
let results = [];
results.push({
fileEntry,
mimeType: 'image/jpeg'
});
return results;
})
.catch(this.ExceptionService.observableCatcher('error'));
}
从诺言中,我可以获得contentURI,并且需要调用使用回调的this。$ window.FilePath.resolveNativePath方法。它应该返回到下一个map方法的绝对路径。
如何在返回的Promise和解析的map方法之间链接回调方法?
您可以用来bindCallback
为回调创建一个可观察对象:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/bindCallback';
...
.map((contentURI: string) => {
const bound = Observable.bindCallback((
path: string,
callback: (result: string) => void
) => this.$window.FilePath.resolveNativePath(path, callback));
return bound(contentURI);
})
...
我使用了arrow函数,以便参数类型是显式的,并且可以resolveNativePath
在上调用this.$window.FilePath
。
我没有使用过Function.prototype.bind
,因为它返回any
并且确实与TypeScript的bindCallback
函数类型推断有关。
上面的答案使用RxJS5。但是,您添加到问题中的其他信息表明您正在使用版本4。在该版本中,该函数名为fromCallback
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句