Angular8 rxjs6 how to wait for results of subscribe in a service

pengz

I am building an application in Angular8 and rxjs6. I am working on separating out logic from one large component into a service.

I am using the combineLatest function to get the results of multiple observables. Then inside the body of combineLatest subscribe(=>{}) the results data is used to update multiple BehaviorSubjects.

The issue I am running into is that I need to make sure those BehaviorSubjects get the latest data first before moving onto the next statements in the component.

The combineLatest code works fine in the body of the component because I can put the rest of the logic inside the body of subscribe. However, I want to move the combineLatest logic to a service, therefore I need to be able to wait for the logic inside of subscribe() to be completed before moving onto the next statements in the component.

Other similar questions suggest the use of map() or returning an observable of(). However none of these solutions seem to work.

I am trying to return a wrapper function around combineLatest as an observable and then subscribe to that inside the component. However it is not working correctly.

Service

import { Observable, BehaviorSubject, combineLatest, throwError } from 'rxjs';

  // Create a BehaviorSubject to track and share updates to People Options
  peopleOptions: any = {};
  peopleOptionsResponse = new BehaviorSubject(this.peopleOptions);
  peopleOptionsObservable = this.peopleOptionsResponse.asObservable();

  // Create a BehaviorSubject to track and share updates to Projects Options
  projectsOptions: any = {};
  projectsOptionsResponse = new BehaviorSubject(this.projectsOptions);
  projectsOptionsObservable = this.projectsOptionsResponse.asObservable();

  getSharedOptions(): Observable<any> {

    // Combine results of multiple observables
    return combineLatest([
      // Get current value of Record Detail subject
      this.getProjects().pipe(catchError(err => {
        console.error(`getProjects failed ${err}`);
        return throwError(err);
      })),
      this.getPeople().pipe(catchError(err => {
        console.error(`getPeople failed ${err}`);
        return throwError(err);
      }))
    ]).subscribe(results => {

      // Get projects select options
      let projectsOptions = results[0];
      // Update current value of Projects Options behavior subject to share with subscribers
this.projectsOptionsResponse.next(projectsOptions);

/* The logic in the component that uses the behavior subjects' data should execute after this is complete only */
        });
      }

Component

this.exampleService.getSharedOptions().subscribe(result => {
/* Component logic that uses the current data in the behavior subjects which were updated in the service's getSharedOptions combineLatest subscribe body */
});

Error message:

this.exampleService.getSharedOptions(...).subscribe is not a function
user2216584

this.exampleService.getSharedOptions(...).subscribe is not a function

This is happening because getSharedOptions is not returning an Observable, instead, it returns a Subscription instance.

To fix the issue lets change your getShareOptions() method like this:

getSharedOptions(): Observable<any> {

// Combine results of multiple observables
return combineLatest([
  // Get current value of Record Detail subject
  this.getProjects().pipe(catchError(err => {
    console.error(`getProjects failed ${err}`);
    return throwError(err);
  })),
  this.getPeople().pipe(catchError(err => {
    console.error(`getPeople failed ${err}`);
    return throwError(err);
  }))
]).pipe(
 tap(results => {
  // Get projects select options
  let projectsOptions = results[0];
  this.projectsOptionsResponse.next(projectsOptions);
 })
);

And then in component -

this.exampleService.getSharedOptions().subscribe(result => {
/* Component logic that uses the current data in the behavior subjects which were updated in the service's getSharedOptions combineLatest subscribe body */
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Is it possible to share subscribe event in rxjs6 and angular?

Angular 7 (RxJs6) - Unit tests - How to check if service return throwError?

How to subscribe service in Angular

call and wait in interval using subscribe in Angular 6

how to wait for http request for returning response with in subscribe method in angular 8?

rxjs6 ActivatedRoute subscribe to observable

Refactor nested subscribe with conditional rxjs6

How to wait for subscribe to finish?

rxjs6 Timer not being triggered in Angular 6 subscription to observable timer placed in service

How to return value from subscribe of forkJoin with angular 6 and RxJs 6?

How to wait to finish subscribe before moving to next index in for loop in Angular 6

How to subscribe to an event on a service in Angular2?

Angular 6: subscribe component to a service event

How to make a generic request service in Angular8

How to subscribe to the DataTableFactory service?

Wait until a subscribe is called in angular

How to fix " Property 'wheelDelta' does not exist on type 'WheelEvent' " while upgrading to angular 7,rxjs6?

How to Subscribe From service in angular 6, I am getting undefind error

How to use combineLatest with flatMap in rxjs6?

How to use rxjs6 partition in typescript?

Angular Map and mergeMap rxjs6 operators

rxjs 6 countdown timer subscribe angular 6

angular RXJS how to cast subscribe response type

How to use subscribe-next RxJS in Angular?

How to wait for the information to be received by the service and then use it in angular

How to subscribe object from service in Angular 2/5?

How to correctly subscribe to a service that is making different HTTP get requests? [Angular]

How to Subscribe window.resize from an angular Service?

How to access value outside the .subscribe in angular 2 polling service

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive