Function that returns an Observable

In my typescript code, I have a function that looks like this:

getConfigurations() {
    let sessionConfig = sessionStorage.getItem('config');
    if(sessionConfig)
        return of(sessionConfig);
    else {
        this.dataService.getRoute('configurations').subscribe(
            route => {
                this.http.get<any[]>(route.ToString()).subscribe(
                    result => {
                        sessionStorage.setItem('config', result);
                        return of(result);
                    },
                    error => {
                        alert(error);
                    }
                )
            },
            error => {
                alert(error);
            }
        );
    }
}

This function is supposed to either return a string value if the 'config' key in sessionStorage already exists or retrieve the value from the backend using dataService and save it in the session storage. However, I am having trouble returning the value stored in sessionStorage (result) as well.

The getRoute function from dataService looks like this:

getRoute(service: string){
    return this.http.get('urlToMyBackendWebApi');
}

Here, http refers to the Angular HttpClient.

I am wondering how I can access the value returned by getConfigurations(). I tried subscribing to getConfigurations(), and retrieving the value from the if condition works fine, but I'm unsure about how to get the result from the else condition. Should I return an observable for the entire block? If so, how would I go about reading the return value?

Answer №1

Avoid subscribing to the observable, instead return it and utilize the tap operator for saving the response:

retrieveConfigurations() {
    let sessionConfig = sessionStorage.getItem('config');
    if(config)
        return of(sessionConfig);
    else {
        return this.dataService.getRoute('configurations').pipe(
          mergeMap(route => this.http.get<any[]>(route.ToString()),
          tap(result => sessionStorage.setItem('config', result))
        );
    }
}

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

Modify the class of the dropdown and heading 2 elements if they meet specific conditions using Animate.css

Is it possible to add a class using jQuery when two specific conditions are met? 1) If the dropdown selection is either "acting" or "backstage" 2) If the membership status is set to "Non-member" If both of these requirements are fulfilled, I would like ...

Is there a standardized method for obtaining a date in the format of six digits as YYMMDD?

In my current project, I'm developing a function that generates a list of dates represented in a 6-digit format beginning from the present day up until August of 2018. The desired output should resemble the following: [190322, 190321, 190320, ...] I ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Send information to the next route using Vue

Within my Vue frontend, there is a method called `moveToOrder` which asynchronously communicates with the backend to process a move from the cart collection to the orders collection: methods:{ async moveToOrder() { const res = await this.$axios.g ...

What is stopping me from sending data via POST - Express?

I'm encountering an issue with Express [POST request]: I have developed server-side and client-side code to send data to both the terminal and the browser.. Unfortunately, I am unable to view the result of the post function!! Please assist me, I feel ...

Unpredictable hues in a headline

Can the text in an H1 tag have each word appear in a different random color, and then refresh to show new random colors? I have 5 specific colors in mind that I'd like to use. How would I go about coding this? ...

Enhance your coding experience with Visual Studio Resharper using TypeScript and node_modules

Currently using Visual Studio 2015 Update 3 and encountering an issue with Resharper when trying to Refactor TypeScript code. Resharper is attempting to refactor code in all folders, including the node_modules directory. This poses a problem as I do not wa ...

Skipping beforeRouteLeave in VueJS

In my Vue SPA, there is a component where I am using the beforeRouteLeave guard to prevent accidental page exits. However, within this component, I occasionally make an ajax request that, upon successful completion, needs to redirect the user to another lo ...

Difficulty in switching state value from true to false in ReactJS

As a newcomer to the world of reactjs, I am currently experimenting with setting the state of input_active to true or false depending on onBlur and onFocus events. This allows me to dynamically change the style of the input element. Here is a snippet of t ...

The email address [email protected] is in need of a jasmine peer version equal to or greater than 3, yet there are no such

After upgrading jasmine-core to version 3.1.0, I decided to also update karma-jasmine-html-reporter to the latest version 1.1.0 npm i --no-optional This command resulted in: npm WARN [email protected] requires a peer of jasmine@>=3 but none ...

Retrieving input data when utilizing ng-file-upload

I need help with uploading images and their titles using ng-file-upload in the MEAN stack. I am able to save the image successfully, however, I'm facing difficulty in retrieving the data sent along with it. Controller: module.exports = function ($sc ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

Tips for managing the response from a POST request using jQuery

I'm currently working on sending data via POST to my ASP.Net MVC Web API controller and retrieving it in the response. Below is the script I have for the post: $('#recordUser').click(function () { $.ajax({ type: 'POST', ...

Error: An unexpected closing tag "<p>" was encountered while parsing the template

I am facing an issue while trying to format an XML file in Angular. Here is the code snippet I attempted to use: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Raw Request</b> <pre& ...

Node.js project is set up globally on personal system

Introduction I'm diving into the world of Node.js and eager to learn. NPM has been a game changer for me as I can easily install packages globally and utilize them as standalone applications accessible from anywhere on my system. To my surprise, thi ...

I am interested in creating a get and set method using the arrow function

Currently utilizing typescript 3.1.6. Is it possible to define get and set methods using arrow functions like this: export class foo { /* attributures ... */ /* constructor ... */ /* ---- Example ---- */ get bar = ():string => this.anAttributeToGe ...

Incorporate a single md-switch to control various other md-switches within an HTML/JS setup

I am looking to implement a feature that allows users to toggle entire group sections on and off. When a group section is toggled off, I want the individual sections within that group to also be disabled. Conversely, when a group section is toggled on, I w ...

Executing the `process.nextTick` function throws an error, causing the message: "Headers cannot be set once they have been sent."

I'm attempting to retrieve data from MongoDB within a Node.js file. I am encountering the following error: /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); Error: Can't ...

Removing a value from a JSON object by utilizing the .map function

My JSON object is structured as follows: [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}] I am attempting to remove the element "child":[{"boxId":2} with boxId=2 from the object. I have tried using a , ...

Embed an array within a div using JavaScript

I'm looking to make a small adjustment to this code, acknowledging that it's far from perfect. Instead of simply writing the array contents into a single div, I'd like to create a new div for each number in the array and then add it to the c ...