Storing array data locally within an AngularJS application for seamless sharing between two separate applications

I need assistance with persisting and sharing array data var queries = []; between two separate AngularJS applications. One application is for the front end, while the other is for the admin side. Both applications cause the entire page to load when accessed.

I attempted to use the code below to share the data, but unfortunately, it's not working as expected:

.factory('QueryService', function() {
        var queries = [];
        var factory = {};
        //..
    factory.addQuery = function(query) {
          queries.push(query);
        localStorage.setItem('queries', JSON.stringify(queries));
        console.log(JSON.parse(localStorage.getItem('queries')));
        return JSON.parse(localStorage.getItem('queries'));
    };
    //..
    return factory;
}

The above code only retrieves the last element added to the queries array.

I also tried using angular-local-storage, but encountered the same issue.

.factory('QueryService', ['localStorageService', function(localStorageService) {
        var queries = [];
        var factory = {};
        //..
    factory.addQuery = function(query) {
          queries.push(query);
        localStorageService.set('queries', queries);
        console.log(localStorageService.get(('queries')));
        return localStorageService.get(('queries'));
    };
    //..
    return factory;
}

I require the array queries data to be accessible in both the front end and admin applications.

Can anyone provide guidance on how to achieve this?

Answer №1

Utilize the factory function to establish private variables specifically for that factory, allowing you to both set and retrieve the value of those private variables.

If needed, you could also create an additional method to clear the queries variable.


    .factory('QueryService', function () {
        var queries = [];
        var factory = {};

        return {
            addQuery : function (query) {
                queries.push(query);
                localStorage.setItem('queries', JSON.stringify(queries));
                console.log(JSON.parse(localStorage.getItem('queries')));
                return JSON.parse(localStorage.getItem('queries'));
            },
            fetchQuery : function ( ) {
                return localStorage.getItem('queries');
            }
        };
    });

Answer №2

Give this a shot:

// store data in localStorage
localStorage.myData = angular.toJson(data);


// get data from localStorage
var data = angular.fromJson(localStorage.myData);

Please inform me of the outcome.

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

Is it possible to configure Nginx mime types within a Docker container?

My docker-compose.yml file looks like this: version: "1.0" services: web: container_name: webserver image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - ./frontend:/frontend ports: - "8001:80&qu ...

Switch up the blogs displayed depending on the category chosen using React

I seem to have hit a roadblock with my current issue. My challenge involves organizing and displaying blog posts according to their categories: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory ...

Steps for deactivating AMD on four files and sequentially loading them using webpack

I am facing an issue where I need to disable AMD on 4 files and ensure that video.js is loaded before the other 3 files, as they are dependent on it. My attempt to achieve this in webpack.config.js was unsuccessful: const path = require('path') ...

Strategies for aligning tooltips with the locations of dragged elements

One of my projects involves a simple drag element example inspired by Angular documentation. The example features a button that can be dragged around within a container and comes with a tooltip. <div class="example-boundary"> <div ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

Performing bulk operations on multiple documents in MongoDB by specifying a custom identifier for updating or

Recently, I've been working with a mongo schema const taskSchema=new Schema({ userID:{type:ObjectId,required:true}, task: { type: String, required: true, trim: true, maxlength: 30, }, finalDate:{type:Date,required:true}, ...

Issue with Highcharts failing to render points on regular intervals

I am facing an issue where the line graph in my frontend application using highcharts disappears or fails to draw to the next new data point every 30 seconds. Can anyone provide insight into why this might be happening? Check out the fiddle: http://jsfidd ...

`Some Items Missing from Responsive Navigation Menu`

Hey there! I'm currently diving into the world of responsive design and I'm attempting to create a navigation bar that transforms into a menu when viewed on a mobile device or phone. Everything seems to be working fine, except that not all the na ...

What is the best way to store client-uploaded files on the client-side using Bootstrap forms and Express server code?

Essentially, the user submits a file for upload, which is then saved on the client-side (I believe this is handled by PHP), and the upload form I am utilizing is a Bootstrap HTML form. On the server side, I am writing my code with Express. I'm feeling ...

Ways to retrieve the chosen option from a dropdown menu within an AngularJS controller

I have a drop down (combo box) in my application that is populated with values from a JSON array object. Can someone please explain how to retrieve the selected value from the drop down in an AngularJS controller? Appreciate the help. ...

Utilizing Restangular to refine search results with filters

I need help troubleshooting an issue with my Restangular query. Despite trying various methods, I am unable to retrieve filtered data successfully. Here are the different approaches I have attempted: $scope.welcomes = Restangular.all("projects").getList({ ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

Learn how to dynamically deactivate a radio button in AngularJS by utilizing the ng-repeat directive

I have been working on some code in Angular JS and need to disable a radio button based on the previous selection or changes in a text box In the JS controller: PPCO.cusGender = [ { id : '1', key : 'Male', value : 'Male', dis ...

The differences between using the opacity attribute in HTML and the opacity property

There are two distinct methods for adjusting opacity in HTML: <div opacity="0.5"></div> and <div style="opacity: 0.5;"></div> I am familiar with setting these values in JavaScript as well: div.setAttribute("opacity", 0.5); and ...

The display function in Javascript has a tendency to work sporadically

I’ve been tasked with creating my own tic tac toe game through coding. While I am relatively new to programming, I have a strong passion for it. At the moment, I've set up a basic function to hide only the "O", leaving only the "X" visible on the gr ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

Link components in Next.js now automatically add the current path when working with nested dynamic routes, making it

How can I effectively handle nested dynamic routes and utilize the Next.js Link component? Let's say I have 2 different file paths: /pages/projects/index.js <Link href={`/projects/${project.id}`} key={index}> <a>Project Name</a> ...

Is there a way to illuminate a complete row by simply hovering over a span within one of the columns?

If I want to change the background-color of a div with classes "row" and "highlightThisRow" when hovering over a span with the class "fromThisSpan", how can I achieve that? In a list, there are multiple rows with several columns. The span in question is l ...