简体   繁体   中英

How to call a http Observable inside a subscription to another Observable?

I have a subject that is subscribed to and fires when a user searches.

let searchView;
this.searchSubject
      .switchMap((view: any) => {
          searchView = view;
          this.http.post(this.url, view);
      })
      .subscribe(page => {
          this.searchHistoryService.addRecentSearch(searchView).subscribe();
      })

searchHistoryService.addRecentSearch records this search so the user can see their recent searches.

I don't think this is good practice as the observable is subscribed to everytime, I would rather use a subject which I'm calling .next() on, or combine the history call with the search call itself.

If searchHistoryService.addRecentSearch returns a Subject I can call .next() but where would I subscribe to it?

I tried adding this in the searchHistoryService's constructor

this.searchHistorySubject.do(observableIWantToCall()).subscribe()

and then replacing the subscription to 'addRecentSearch' with this:

this.searchHistoryService.searchHistorySubject.next(searchView)

But it doesnt work.

The inner observable, observableIWantToCall() gets called but the observable returned isnt subscribed to.

What's wrong with this and what is best practice for subscribing to an observable when another is finished emitting?

I think you can do something like this:

let searchView;
private searchHistorySubject$: Subject<any> = new Subject<any>();

constructor(){
   this.searchHistoryService.addRecentSearch(searchView).first().subscribe(
     response => {
        //It will entry when you send data through next
     },
     error => {
       console.log(error);
     }
   );
}

...

addRecentSearch(searchView) {
    ...
    return this._searchHistorySubject$.asObservable();
}

setSearchHistoryEvent(value: any) {
  this._searchHistorySubject$.next(value);
}

this.searchSubject
      .switchMap((view: any) => {
          searchView = view;
          this.http.post(this.url, view);
      })
      .subscribe(page => {
          this.searchHistoryService.setSearchHistoryEvent(searchView);
      }
)

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