首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular - Piping从具有条件的方法调用中返回了observable -无法读取未定义的属性“”subscribe“”

Angular - Piping从具有条件的方法调用中返回了observable -无法读取未定义的属性“”subscribe“”
EN

Stack Overflow用户
提问于 2021-04-15 22:39:23
回答 1查看 59关注 0票数 0

我正在尝试通过管道传递从组件的save方法返回的可观察对象。

在这个基于条件的save方法中,会打开一个对话框,等待用户输入,然后再调用update端点并将结果作为observable返回,最后由save()方法返回。

问题是,我试图通过管道传递save()的结果,以检查值是否已发出,然后离开组件。因为.subscribe()在返回值之前执行。

代码摘要如下所示:

代码语言:javascript
复制
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)
 }
}

然后由另一个方法调用

代码语言:javascript
复制
  onSaveButtonClick() {
    this.save().subscribe();
  }

我遇到的问题是,当地址发生更改并打开对话框时,由于.subscribe()方法尚未返回任何内容,我在save()方法上得到了一个错误。

任何帮助都将不胜感激,因为我已经挠头好一阵子了。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-04-16 02:17:57

当使用map()时,你总是需要返回一些东西。在某些情况下,您不会返回任何内容。至少返回null

代码语言:javascript
复制
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)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67110577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档