我需要将回调方法链接到 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'));
}
从 promise 中,我可以获得一个 contentURI,我需要调用 this.$window.FilePath.resolveNativePath 使用回调的方法。它应该返回下一个映射方法的绝对路径。
如何在返回promise和解析map方法之间链接回调方法?
最佳答案
您可以使用 bindCallback
为回调创建一个 observable:
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);
})
...
我使用了一个箭头函数,因此参数类型是显式的,因此
resolveNativePath
被调用 this.$window.FilePath
.我没用过
Function.prototype.bind
,因为它返回 any
并且真的与 TypeScript 对 bindCallback
类型的推断相混淆。功能。上面的答案使用 RxJS 5。但是,您添加到问题中的附加信息表明您使用的是版本 4。在该版本中,该函数名为
fromCallback
.
关于Rxjs,如何将回调方法链接到 Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43131385/