aRtoo
aRtoo

Reputation: 1892

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

Upvotes: 1

Views: 77

Answers (1)

supersighs
supersighs

Reputation: 947

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

Upvotes: 1

Related Questions