簡體   English   中英

Angular - 管道從其中包含條件的方法調用返回可觀察的 - 無法讀取未定義的屬性“訂閱”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM