【发布时间】:2019-01-27 15:48:24
【问题描述】:
我正在使用 Angular 服务来允许用户上传文件。
服务的实现正在运行;我的问题是关于 RxJS 及其可管道操作符,但这里是服务签名以防万一:
askUserForFile(): Observable<File>;
toBase64(file: File): Observable<string>;
isFileValid(file: File, configuration?: { size?: number, extensions?: string | string[] }): boolean;
对该服务的调用如下:
this.fileService
.askUserForFile()
.pipe(
// this is the operator I'm looking for
unknownOperator(file => this.fileService.isFileValid(file, { extensions: ['txt'] }))
mergeMap(file => {
fichier.filename = file.name;
return this.fileService.toBase64(file);
}))
.subscribe(base64 => {
fichier.base64 = base64;
// Rest of my code
}, error => {/* error handling */});
我想找到一个运算符来代替unknownOperator,如果不满足条件,它将引发错误。
我试过了
-
filter: 如果条件不满足,代码在它之后停止, -
map:即使throwError抛出错误,代码也会继续
我考虑过使用以下管道
.pipe(
map(...),
catchError(...),
mergeMap(...)
)
我认为这可能可行,但我想(如果可能)找到一个缩短此管道的操作员。
有可能吗?如果没有,有更好的管道吗?
【问题讨论】:
-
我只需在
mergeMap中调用isValidFile,如果它返回一个错误值,要么返回一个throwErrorobservable,要么只返回一个错误throw。 -
@cartant 它也可以,谢谢,但我希望能够为此使用运算符,我认为这样会更干净
标签: angular typescript rxjs rxjs-pipeable-operators