Angular 12/rxjs/observables:链式订阅函数:return 语句和错误处理
Angular 12/rxjs/observables: function with chained subscriptions: return statement and error handling
我需要一个可以订阅的功能,returning:
- 如果所有操作都成功,则可观察到结果
- 在所有其他场景中为空字符串的可观察对象
foo(): void {
this.uploadImage.subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
this.httpHandler.uploadImage(this.file).subscribe(
(result) => {
if (result) {
this.httpHandler.verifyUpload(result.uploadId).subscribe(
(res) => {
if (res) {
return of(res.url);
} else {
return of('');
}
});
} else {
return of('');
}
}
);
} else {
return of('');
}
}
- 我的函数缺少结束 return 语句,老实说我不知道如何解决这个问题
- 我不会return万一出错
- 很乱,我只是想return一个空字符串 Observable 如果操作没有按预期完成
提前致谢
编辑:基于反馈的最终工作版本:
foo(): void {
this.uploadImage().subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
return of(''):
}
return this.httpHandler.uploadImage(this.file).pipe(
switchMap(result => {
if (result) {
return this.httpHandler.verifyUpload(result.uploadId)
} else {
return of('');
}
}),
map((res: any) => res.verified?.url || ''),
catchError(() => of(''))
);
}
您可以使用 switchMap
& map
运算符来实现,如下所示:
foo(): void {
this.uploadImage().subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
this.httpHandler.uploadImage(this.file).pipe(
switchMap(result => {
if (result) {
return this.httpHandler
.verifyUpload(result.uploadId)
.pipe(map(res => res?.url || ''));
} else return of('');
})
);
} else {
return of('');
}
}
我需要一个可以订阅的功能,returning:
- 如果所有操作都成功,则可观察到结果
- 在所有其他场景中为空字符串的可观察对象
foo(): void {
this.uploadImage.subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
this.httpHandler.uploadImage(this.file).subscribe(
(result) => {
if (result) {
this.httpHandler.verifyUpload(result.uploadId).subscribe(
(res) => {
if (res) {
return of(res.url);
} else {
return of('');
}
});
} else {
return of('');
}
}
);
} else {
return of('');
}
}
- 我的函数缺少结束 return 语句,老实说我不知道如何解决这个问题
- 我不会return万一出错
- 很乱,我只是想return一个空字符串 Observable 如果操作没有按预期完成
提前致谢
编辑:基于反馈的最终工作版本:
foo(): void {
this.uploadImage().subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
return of(''):
}
return this.httpHandler.uploadImage(this.file).pipe(
switchMap(result => {
if (result) {
return this.httpHandler.verifyUpload(result.uploadId)
} else {
return of('');
}
}),
map((res: any) => res.verified?.url || ''),
catchError(() => of(''))
);
}
您可以使用 switchMap
& map
运算符来实现,如下所示:
foo(): void {
this.uploadImage().subscribe(res => console.log('url: ' + res));
}
uploadImage(): Observable<string> {
if (isValid(this.file)) {
this.httpHandler.uploadImage(this.file).pipe(
switchMap(result => {
if (result) {
return this.httpHandler
.verifyUpload(result.uploadId)
.pipe(map(res => res?.url || ''));
} else return of('');
})
);
} else {
return of('');
}
}