在子订阅中返回parent observable
问题描述:
我正试图return
从另一个observable的订阅中获得布尔值。然而,我不能让return
泡泡到父方法。在子订阅中返回parent observable
我知道我是return
在订阅的上下文中,但我如何告诉canDeactive
dialog.result.subscibe
订阅完成并且能够返回布尔值?
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
const settings: DialogSettings = {
title: 'Please confirm',
content: 'Are you sure want to leave without saving your changes?',
actions: [
{ text: 'No'},
{ text: 'Yes', primary: true }
]
};
if (!this.isSaved && this.updatedPositions.length) {
// return confirm('Do you want to discard the changes?');
const dialog: DialogRef = this.dialogService.open(settings);
dialog.result.subscribe((result: DialogResult) => {
if (!(result instanceof DialogCloseResult) && result['text'] === 'Yes') {
console.log('action', result);
console.log('returning false');
return false;
} else {
console.log('dialog.close()');
dialog.close();
return true;
}
})
} else {
console.log('else');
return true;
}
}
答
dialog.result
类似于从这明显着反映到主要方法回调返回一个异步call.Its。实际上,您在true
部分通话中没有返回任何内容。
不要订阅更改,照原样返回可观察值。使用地图来转换数据。
return dialog.result.map((result: DialogResult) => {
if (!(result instanceof DialogCloseResult) && result['text'] === 'Yes') {
console.log('action', result);
console.log('returning false');
return false;
} else {
console.log('dialog.close()');
dialog.close();
return true;
}
})
并保持它一致,在主要的其他部分,在最底部。返回一个Observable。
} else {
console.log('else');
return Observable.of(true);
}