如何以angular

时间:2019-04-21 03:03:55

标签: angular rxjs

如何返回在注射剂上调用的订阅旅馆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方法的返回值。

所以这是我的解决方案。这是workinng,但我不知道这是否正确。

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是单线程的或“异步的”

1 个答案:

答案 0 :(得分:1)

您的第一个示例显示您正在尝试返回可观察的对象。这就是您使用rxjs通过提供的内容进行操作的方式。这利用了rxjs filtermap。您可能不想直接返回订阅,而是订阅函数返回的可观察对象。

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])
    );
}