簡體   English   中英

如何以角度返回訂閱

[英]How to return a subscription in angular

您如何在 Angular 中返回在可注入對象上調用的訂閱?

所以我一開始花了一個小時才弄明白的事情是這樣的:

 returnURLNotes(): Observable<any> {
    return this.store.select(selectDentureDesignNotes).subscribe((notes) => {
      if (
        notes &&
        notes[this._CANVAS_NAME] &&
        notes[this._CANVAS_NAME].length > 0
      ) {
        return notes[this._CANVAS_NAME];
      }
    });
  }

看到第一個返回了嗎? 我剛剛返回了store.selector並且這種方法不起作用。 因為內部返回將不能用作returnURLs方法的返回值。

所以這是我的解決方案。 它正在工作,但我不知道這是否是正確的方法。

returnURLNotes(): any {
    let URLs = {};
    const URLNotes$ = this.store.select(selectDentureDesignNotes);
    URLNotes$.subscribe((notes) => {
      if (
        notes &&
        notes[this._CANVAS_NAME] &&
        notes[this._CANVAS_NAME].length > 0
      ) {
        URLs = notes[this._CANVAS_NAME];
      }
    });

    return URLs;
  }

但我不認為這是正確的方法,因為 JS 單線程或“異步”。

您的第一個示例顯示您正在嘗試返回一個 observable。 這就是您將如何使用 rxjs 使用您提供的內容來做到這一點。 這利用了 rxjs filtermap 您可能不想直接返回訂閱,而是訂閱您的函數返回的 observable。

returnURLNotes(): Observable <any> {
    return this.store.select(selectDentureDesignNotes).pipe(
        filter(notes => notes &&
            notes[this._CANVAS_NAME] &&
            notes[this._CANVAS_NAME].length > 0),
        map(notes => notes[this._CANVAS_NAME])
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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