Creating an Angular service that checks if data is available in local storage before calling an API method can be achieved by implementing a

I am currently working on developing an Angular service that can seamlessly switch between making actual API calls and utilizing local storage within a single method invocation.

component.ts

this.userService.getAllUsers().subscribe(data => {
    console.log('users', data); //getUser
});

user.service.ts

export class UsersService {

constructor(...){ }

getAllUsers() {
    return this.storageMap.get('users').pipe(
    switchMap(data => {
        if (data) return data;
        else return this.userStore.collection('users').valueChanges();
    })
    );
}

saveUsers(data){
return this.storageMap.set('users', data);
}

}

Local storage library: @ngx-pwa/local-storage

Issues:

  1. I am unsure how to return "data" as an Observable from the "getAllUsers" method if it is available in storageMap.

  2. How can I execute the "saveUsers" method to store data in local storage within "getAllUsers" if the data is undefined.

Thanks in advance!

Answer â„–1

One way to transform information stored in LocalStorage into a stream of data is by applying the RxJS of operator.

import { of } from 'rxjs';
.
.
const observableData = 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

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Instead of displaying the location attribute in an alert, populate it into a text area

I have a function that can retrieve my current location using longitude and latitude coordinates. However, I am looking to automatically fill a text area (Populate Here) with the results instead of displaying an alert. <!DOCTYPE html> <html> ...

Develop a Vue component for a fixed sidebar navigation

I am in need of a vertical navigation bar positioned to the left of my app's layout, with the content extending across the right side. However, I am currently facing an issue where the navbar is pushing all the content downwards. How can I resolve thi ...

Scrolling through image galleries with automatic thumbnails

I am looking to create an automatic image scrolling feature on my webpage using a bunch of images I have. I have searched for a solution but have not found one that fits my requirements. I don't think a carousel is the right approach for this. The sol ...

What is the specific reference of the first parameter in NLS localize?

Regarding the question on localizing VSCode extensions, I am also curious why the localize function requires two parameters. When it comes to localizing settings, it's a simple process of replacing literal values with tokens surrounded by percent sig ...

Getting the values of $scope variables from AngularJS in the controller to the view

I have a simple scope variable on my AngularJS Controller. It is assigned a specific endpoint value like this: $scope.isItAvailable = endpoint.IS_IT_AVAILABLE; How can I properly use it in my view (HTML) to conditionally show or hide an element using ng- ...

Encountered a XHR error (404) while attempting to load the script from https://unpkg.com/[email protected]/operators/index.js/first

Struggling with implementing the Google Material input control in angular2, I keep encountering a recurring error in the browser console. https://i.stack.imgur.com/Q5YFA.png: Upon inspecting my 'node_modules' directory, I noticed the presence o ...

React Query mutation encountered a TS2554 error: Type argument was not valid

I'm a beginner when it comes to TypeScript and I am using react-query. I tried using mutate, but it is causing an error. TS2554: Expected 1-2 arguments, but got 3. interface: interface ChangePassword{ email: string; password: string; conf ...

Guidance on retrieving a boolean value from an asynchronous callback function

I'm looking to determine whether a user is part of a specific group, but I want the boolean value returned in the calling function. I've gone through and debugged the code provided below and everything seems to be working fine. However, since my ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

What is the best way to extract just the hours and minutes from a timestamp column that includes hours, minutes, and seconds in my dataset and create a new column

Is there a way to extract only the hour and minute values from a timestamp column that includes seconds in my dataset? ...

Tips for removing a DOM element in Selenium using Java

Recently, I've been attempting to remove an element from a website using Selenium and Java with the xpath of the element readily available. WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'discord.gg/')]")); The specific e ...

Oops! There seems to be an issue with trying to access the 'map' property of undefined within the render method

While working on my project, I encountered an issue with a table from react material ui. The problem arises when attempting to populate the table with data from the state, resulting in an error message stating "cannot read property 'map' of undef ...

Angular - Organize an array of Objects in alphabetical order

Here is the JSON that I'm working with: { "groups": { "1567310400000": [ { "groupName": "Fruits", "documentCount": 5 }, { "groupName": "Vegetables", ...

What is the process to retrieve a variable from a Node.js file in an HTML document?

What is the best way to showcase a variable from a node.js route in an HTML File? I have a node.js route structure as follows: router.post("/login", async (req,res) => { try { const formData = req.body const name = formData.name ...

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Components in Angular modules that are loaded lazily with identical names

I have developed an Angular application with multiple lazy-loaded modules. Each of these modules contains different components that are conceptually similar but vary in content. For example, each module may have its own "home" component. Is it advisable t ...

Combining SlateJS with Redux

I need to store the value of a SlateJS editor in redux instead of state, but when I modify the hasLinks method, I encounter an immediate crash with the error message: TypeError: Cannot read property 'inlines' of undefined Modified Editor&apos ...

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...