Avoid passing the observable to return values from the service layer to the component

I am currently attempting to pass the outcome of a service layer with regard to components.

The service that connects with the API:

 public getPerfilNew$(): Observable<PerfilInvestidor> {
            return this.http.get<PerfilInvestidor>(`${environment.api.basePosicaoConsolidada}/consolidado`)
              .pipe(
                map(res => res),
                shareReplay(1),
                catchError(err => {
                    console.log('Error in perfil', err);
                    return throwError(err);
                })
            )
        }

public getPositionConsolidated(): Observable<PosicaoConsolidada> {
    return this.http.get<PosicaoConsolidada>(`${environment.api.basePosicaoConsolidada}/consolidado`)
      .pipe(
        map(res => res),
        shareReplay(1),
        catchError(err => {
            console.log('Error investiments', err);
            return throwError(err);
        })
    )
}

In my component, I attempted the following:

public loadData() {
        // Determine if the profile retrieval failed or not
        this.homeGuardService.getPerfilNew$.pipe(
            takeUntil(this.unsubscribe) 
        ).subscribe(res => {
            this.perfilInvestidor = res;
            this.perfilFailed = this.perfilInvestidor.status ? true : false;
            console.log('perfil is failed --->', this.perfilFailed)
        })

        // Checking for investments
        this.homeGuardService.getPositionConsolidated().subscribe(res => {
            this.positionConsolidated = res
            if (this.positionConsolidated) {
                this.investments = true
            }
        });

        this.isEverthingFailed = !this.investments && this.perfilFailed
}

I need to subscribe external values and match them into my variable isEverythingFailed. Should I use Subject? BehaviorSubject? Because in this way, the variables investments and perfilFailed are undefined.

With this number of observables, am I compromising memory usage? Open to suggestions.

Answer №1

One way to retrieve data from multiple streams and subscribe to them is by using either forkJoin or combineLatest:

public fetchData() {
  forkJoin([this.userService.getUserDetails$(), this.userService.getAccountInfo()])
    .subscribe(([userDetails, accountInfo]) => {
        this.user = userDetails;
        this.userFailed = this.user.status ? true : false;
        console.log('User failed status --->', this.userFailed)
        this.accountInformation = accountInfo
        if (this.accountInformation) {
            this.accountsLoaded = true
        }
        this.isAllFailed = !this.accountsLoaded && this.userFailed
    })
  )
}

Answer №2

1. Insights

Upon initial inspection, it appears that there may be a race condition occurring in the code provided. It is crucial to understand how Subject operates in this context:

When you create a new Subject and immediately call next() on it without any subscribers attached, the emitted value will not be preserved.

const sub = new Subject();
sub.next(1);

// Subscribing here won't trigger anything
   sub.subscribe(a => console.log(a))
// This is because Subject does not retain previous values

However, if you subscribe before emitting a value like so:

const sub = new Subject();

// Subscribe first:
sub.subscribe(a => console.log(a))

sub.next(1);

// Now you will see the value printed in the console as expected.

In your specific case, it seems like you are subscribing to a subject after it has already emitted values.

Additionally:

 this.perfilClient$.subscribe(res => {

You are subscribing to perfilClient$, but it's unclear where values are being emitted into that stream?

If you struggle to coordinate subscriptions with emissions from a Subject, consider using ReplaySubject or BehaviorSubject for better synchronization.

2. Considerations

Your implementation involves a limited number of observables, but there are some common pitfalls such as:

  1. Nesting subscriptions within each other
  2. Having empty subscription callback functions etc..

In RXJs, it is important to minimize side effects wherever possible to ensure a more streamlined and predictable flow of data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating the world of date pickers: a deceptively easy challenge

Take a look at this fiddle example to get started: http://jsfiddle.net/1ezos4ho/8/ The main goals are: When a date is selected, it should be dynamically added as the input value, like <input type text value="date selected".... Update: <s ...

Tips for implementing a client-side event when an asp:menu item is clicked

Currently, I'm incorporating the <asp:Menu> control into my website and populating it with data from a table in my Sql Server database using an XML data source. Now, I am looking to implement a client-side event when a user clicks on a menu item ...

The error message UnhandledPromiseRejectionWarning is triggered due to a TypeError stating that the function authenticate is

Currently, I am attempting to incorporate basic authentication into my API project using Knex, Express, and MySQL. Here are the functions I have implemented: const users = [{ id:1, username:'selia', password:'fullservice'}] functio ...

Develop a directive for transforming data

In my latest project, I am looking to develop a LoaderDirective that can fetch an observable, display a spinner while loading the data, and then switch to showing the actual data once loaded. I also want it to expose the loaded data using the 'as&apos ...

Utilizing babel-plugin-root-import in conjunction with babel 7

Recently, I decided to dive into setting up Babel 7 for the first time. It's been a bit of a learning curve as I navigate through unfamiliar territory. While I was able to successfully install and utilize @babel/plugin-proposal-optional-chaining, I&ap ...

What is the purpose of specifying the props type when providing a generic type to a React functional component?

When utilizing the @typescript-eslint/typedef rule to enforce type definitions on parameters, I encountered an issue with generically typing a React.FC: export const Address: React.FunctionComponent<Props> = (props) => ( An error was thrown st ...

Troubles with Geocoding functionality on Google Maps integration within Wordpress

I have a challenge where I want to utilize the title of a Wordpress post (a specific location) as a visible marker on a Google map. The code provided by Google successfully displays the map without any markers: <script>function initialize() { va ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

What is the best way to organize products based on the proximity of users using MongoDB's Geospatial Queries

I'm currently working on a web application that connects users with neighbors to buy and sell products. The app is built using node.js, JavaScript, mongodb, and mongoose. My main issue lies in sorting the products. I want to display products from nea ...

Creating a MongoDB query using Mongoose to simulate JavaScript filtering operations (including filter and every) for searching with multiple terms

Introducing a New Search Feature In my current project, I am implementing a search functionality using MongoDB with Mongoose ODM. The existing codebase already has a search feature using JavaScript. Here is a snippet of the code: terms.every((term) => ...

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

Blender Mesh Not Visible in Three.js

After creating a mesh in Blender, I attempted to use it in three.js. Although the file is being loaded according to the event log, all I see is a black screen. How can I ensure that the mesh actually appears on the screen? import * as THREE from 'thre ...

Angular 2 displayed a vibrant HTML page component

In my project, there is an Isotope Component that I want to keep protected from unauthorized access. If a user is not logged in and tries to navigate directly to the Isotope page by entering a specific route like: http://localhost:4200/register and then ...

Changing the URL parameters to accommodate a specific query

Currently, I have set up the route as follows: app.get("/employees", (req, res) => { data.getAllEmployees().then((data) => { res.json(data); }).catch(function(err) { console.log("An error was encountered: " + err); }); }) ...

Interacting with a form in Node.js does not print out the form values to the

I am just starting to learn about node.js and I'm attempting to create a form that includes fields for 'name' and 'department'. However, when I submit the form, both 'name' and 'department' are showing up as &ap ...

Display only the offcanvas button

Having trouble with Bootstrap 5 offcanvas? The offcanvas doesn't hide when I click the button again. <button data-bs-toggle="offcanvas" role="button">Add to Cart</button> Every time I click the button again, the offcan ...

Tips for migrating an AngularJS application to Angular

My current project involves implementing a basic search function using AngularJS (link). I want to integrate this feature into an existing Angular application. To do this, I created a new Angular app and transferred the view to app.component.html. <hea ...

What is the snapping feature of the jQuery Mobile slider?

I've been diving into various sources for the past couple of hours, attempting to implement code snippets claiming to enable snapping functionality on a slider component. I'm facing doubts about the feasibility of achieving this with the jQuery M ...

Display a Carousel in Angular4 based on the selected value from a dropdown

My goal is to create a dynamic carousel that displays a football club's players when the user selects the team from a dropdown menu. The team options are loaded from a database, as well as the player information. Currently, I am able to retrieve the ...