我正在尝试通过管道传递从组件的save方法返回的可观察对象。
在这个基于条件的save方法中,会打开一个对话框,等待用户输入,然后再调用update端点并将结果作为observable返回,最后由save()方法返回。
问题是,我试图通过管道传递save()的结果,以检查值是否已发出,然后离开组件。因为.subscribe()在返回值之前执行。
代码摘要如下所示:
save() : Observable<Address> {
let value = this.form.get('Address').value
if (JSON.stringify(this.address) != JSON.stringify(value.Address)) {
const ref = this.dialog.open(AddressChangeDialog);
ref.componentInstance.canSave = this.form.valid;
ref.afterClosed().pipe(map(result => {
if (result) {
switch (result) {
case AddressChangeDialog.Save:
//Save the form (returns the observable here)
return this.addressService.put(value)
case AddressChangeDialog.Discard:
// Cancel the save
break;
default:
break;
}
}
}));
}
else {
// if the address hasnt changed just save and return the observable
return this.addressService.put(value)
}
}然后由另一个方法调用
onSaveButtonClick() {
this.save().subscribe();
}我遇到的问题是,当地址发生更改并打开对话框时,由于.subscribe()方法尚未返回任何内容,我在save()方法上得到了一个错误。
任何帮助都将不胜感激,因为我已经挠头好一阵子了。
谢谢!
发布于 2021-04-16 02:17:57
当使用map()时,你总是需要返回一些东西。在某些情况下,您不会返回任何内容。至少返回null。
save() : Observable<Address> {
let value = this.form.get('Address').value
if (JSON.stringify(this.address) != JSON.stringify(value.Address)) {
const ref = this.dialog.open(AddressChangeDialog);
ref.componentInstance.canSave = this.form.valid;
ref.afterClosed().pipe(map(result => {
if (result) {
switch (result) {
case AddressChangeDialog.Save:
//Save the form (returns the observable here)
return this.addressService.put(value)
case AddressChangeDialog.Discard:
// Cancel the save
// no return value
break;
// no return value
default:
break;
}
}
// no return value
// You always have to return something. So here we
// return null in case no other return is called before
return null;
}));
}
else {
// if the address hasnt changed just save and return the observable
return this.addressService.put(value)
}
}https://stackoverflow.com/questions/67110577
复制相似问题