简体   繁体   中英

How to return a subscription in angular

How do you return a subscription in Angular that is being called on an injectable?

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. because the inner return won't be available as a return value of returnURLs method.

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."

Your first example shows you are trying to return an observable. This is how you would do that using rxjs using what you have provided. This utilizes rxjs filter and map . You probably dont want to return the subscription directly, but rather subscribe to the observable your function is returning.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM