![](/img/trans.png)
[英]Angular 9 testing component dependant on service with observable - Cannot read property 'subscribe' of undefined
[英]Angular - Piping returned observable from method call which has a conditional in it - Cannot read property 'subscribe' of undefined
我正在尝试 pipe 从组件的保存方法返回的 observable。
在此保存方法中,基于条件打开一个对话框,该对话框在调用更新端点之前等待用户输入,并将结果作为可观察对象返回,然后最终由 save() 方法返回。
问题是我正在尝试 pipe 该 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();
}
我遇到的问题是,当地址更改并打开对话框时,由于 save() 方法尚未返回任何内容,我在 the.subscribe() 上收到错误。
任何帮助都将不胜感激,因为我现在已经摸不着头脑了。
谢谢!
使用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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.