我需要将一个回调方法链接到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'));
}
Run Code Online (Sandbox Code Playgroud)
从promise,我可以得到一个contentURI,我需要调用这个.$ 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);
})
...
Run Code Online (Sandbox Code Playgroud)
我使用了箭头函数,以便参数类型是显式的,因此resolveNativePath可以在this.$window.FilePath.
我没有使用Function.prototype.bind,因为它返回any并且确实扰乱了 TypeScript 推断函数类型的过程bindCallback。
上面的答案使用 RxJS 5。但是,您添加到问题中的附加信息表明您正在使用版本 4。在该版本中,该函数名为fromCallback。