简体   繁体   English

如何以角度返回订阅

[英]How to return a subscription in angular

How do you return a subscription in Angular that is being called on an injectable?您如何在 Angular 中返回在可注入对象上调用的订阅?

So what I did at first that took me an hour to figure out is this:所以我一开始花了一个小时才弄明白的事情是这样的:

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

See the first return?看到第一个返回了吗? I just returned the store.selector and this approach doesn't work.我刚刚返回了store.selector并且这种方法不起作用。 because the inner return won't be available as a return value of returnURLs method.因为内部返回将不能用作returnURLs方法的返回值。

So here's my solution.所以这是我的解决方案。 It's working but I don't know if this is the right way.它正在工作,但我不知道这是否是正确的方法。

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

But I don't feel like that this is the right way because of JS single-threaded or "asynchronousity."但我不认为这是正确的方法,因为 JS 单线程或“异步”。

Your first example shows you are trying to return an observable.您的第一个示例显示您正在尝试返回一个 observable。 This is how you would do that using rxjs using what you have provided.这就是您将如何使用 rxjs 使用您提供的内容来做到这一点。 This utilizes rxjs filter and map .这利用了 rxjs filtermap You probably dont want to return the subscription directly, but rather subscribe to the observable your function is returning.您可能不想直接返回订阅,而是订阅您的函数返回的 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