对于我要从AngularJS重写的应用程序,我需要执行一系列操作:
1) I got to the server to get a message
2) I display the returned message in a generic dialog, with a Yes and No button.
3-Yes) I go to the server to do something, proceed to 4
3-No) I terminate the sequence
4) Notfiy the user that the operation is complete.
我在将其转换为Angular / React Observable
系统时遇到问题。我想做这样的事情:
// Actual arguments are immaterial in this case...
this.webDataService.get('/api/GetEndUserMessage', args)
.pipe(
map((message: string) => {
const config = new MatDialogConfig();
config.data = {
'title': 'Important',
'message': message
};
const dialog = this.matDialog.open(GenericDialogComponent, config);
// If Yes/Ok is clicked, return 'Ok'
// If No/Cancel is clicked, return 'Cancel'
return dialog.afterClosed();
}),
// PROBLEM AREA! ----------------------------------------------
filter((dialogResult: string) => {
if (dialogResult === 'Ok')
return this.webDataService.post('/api/DoSomethingAwesome');
}),
filter((dialogResult: string) => {
if (dialogResult !== 'Ok')
return 'Cancelled'
})
// PROBLEM AREA! ----------------------------------------------
)
.subscribe((result: any) => {
if (result === 'Cancelled')
return;
// Let the user know that the sequence is over. How doesn't matter.
});
问题是,显然它无法编译。
我对React运算符系统的理解充其量是不稳定的,而且我不确定如何调用MatDialogRef.afterClosed()
调用后产生的Observable。
问题:
以什么方式可以按MatDialogRef.afterClosed()
序列使用Observable .pipe
调用的结果?
答案 0 :(得分:1)
当您需要更改可观察流时,请使用switchMap
。 map()
运算符只会使可观察对象发出返回值。
this.webDataService.get('/api/GetEndUserMessage', args)
.pipe(
switchMap((message: string) => {
//...
const dialog = this.matDialog.open(GenericDialogComponent, config);
return dialog.afterClosed();
}),
switchMap((dialogResult: string) => {
return (dialogResult === 'Ok')
? this.webDataService.post('/api/DoSomethingAwesome')
: of('Cancelled')
})
).subscribe((result: any) => { ... });
https://www.learnrxjs.io/operators/transformation/switchmap.html