Issue: The initiation function fails to start data

I have created an app using Ionic framework that displays articles. When a single article is opened, I use the init function in the UserService to initialize user data:

angular.module('coop.services')
.factory('UserService', function(
  $http,
  AppSettings,
  $rootScope,
  $auth,
  $q,
  $resource,
  $cordovaFileTransfer
) {
  var service = {
    user: {},

    init: function() {
      var user = localStorage.getItem('coop_user');

      if (user) {
        service.user = JSON.parse(user);
      }

      service.engagementResource = $resource(
        AppSettings.apiUrl + '/user/:userId/engagements',
        {
          userId: service.user.id
        }
      );
    },

    set: function(user) {
      service.user = user;
      localStorage.setItem('coop_user', JSON.stringify(user));
    },

    get: function() {
      return service.user;
    },
    
    // Other functions...
  
    join: function(engagementId){
      return service.engagementResource.save({
        engagementId: engagementId
      });
    },

    leave: function(engagementId) {
      return service.engagementResource.delete({
        engagementId: engagementId
      });
    },

    getEngagements: function() {
      return service.engagementResource.query();
    }, 

  };

  service.init();

  return service;
});

However, when I access the single article page with a new user, the console shows null for user data instead of actual data.

init: function() {
      var user = localStorage.getItem('coop_user');
       console.log(user);

As a result, my requests to the backend fail because user data is not being sent. During login, I store user data in localStorage in the auth controller like this:

$scope.loginPromise.then(function(response) {
        UserService.set(response.data.user);

The problem is resolved if I refresh the page, as the user data becomes available. How can I resolve this issue?

Answer №1

Begin by activating the Service within your application's execution or from the controller, prior to invoking any additional functions within the service:

ServiceUser.activate();

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

What could be causing the fluctuation in ui-grid height as I scroll horizontally?

After using ui-grid in numerous projects without any issues, I recently encountered a strange issue when working with a large number of columns. With approximately 50 columns, as I scroll from left to right in order to view the columns that are off-screen ...

Why is the oninput function in JavaScript not functioning properly?

After following a practical video tutorial step by step, I tried to implement the code provided (in HTML and JS) but nothing seems to be working! The code snippet from the tutorial includes: var $count = document.getElementById("count"), $textarea = ...

Sending Data from Browser to Node.js using Ajax

I've been struggling to send an AJAX post request to my Node server built with Express for a while now. Despite reading various solutions on similar issues, I couldn't figure out which files to edit. Initially, I attempted using `http.createServe ...

Dynamically loading JQuery causes highcharts to encounter errors

I have limited experience with JavaScript programming, and I've been encountering a persistent issue for quite some time now. Any assistance on this matter would be greatly appreciated. In the provided jsfiddle example, when jQuery is selected from t ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

Looking to add a close button to the iFrame, but having trouble getting it to function when clicked

In my project built with Meteor, I have integrated an iframe to display specific content to the user. The iframe is functioning as expected, but I am looking to add a close button that will effectively unload the iframe when clicked. I attempted to imple ...

Forfeit cookie/session upon page refresh

I am currently working with two separate applications: An AngularJS client running on http://localhost:8080 A NodeJS API server running on http://localhost:3000 The NodeJS API Server solely provides JSON data to the client and does not serve any HTML pa ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

Material-UI rating component outputs a string instead of a numerical value

I'm encountering an issue with the Material UI rating component. Despite providing it with a number as the initial value (this.props.data.feelings_rating), it returns a string whenever I change it within my app. Below is the relevant code: Rating co ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

How can I trigger an onclick event for a link automatically upon loading in Laravel?

I am presenting the link below: <a href="javascript:void(0)" onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a> My goal is for it to change the language of the page (which occu ...

The attribute 'finally' is not found on the data type 'Promise<void>'

I've been attempting to implement the finally method on a promise but continue running into this issue. Property 'finally' does not exist on type 'Promise<void>'. After researching similar problems, I found suggestions to a ...

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

Removing an item from an array depending on a specific condition and index

I am working with an array structure that looks like this: [ {key: 4, data: {…}, qText: {…}}, {key: 4, data: {…}, qText: {…}, isVisible: false}, {key: 5, data: {…}, qText: {…}, isVisible: false}, {key: 4, data: {…}, qText: {…}, isVi ...

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

Select value not updating as expected

I have a select box that is linked to a switch statement in PHP, which changes the order of the results returned from the database based on the value selected in the select box. However, I am facing an issue with my JavaScript not working correctly. Can an ...

Some angles in three.js may cause faces to be obscured

When I work in Blender, my process usually involves creating straightforward models with colored materials. However, when I export these models to Collada format and import them into Three.js, I encounter an issue where some faces do not appear from cert ...

The height of the TinyMCE editor refuses to adjust

Hello, I'm new to utilizing Tinymce within an AngularJS environment. Specifically, I am working with the Tinymce library version 4.3.13. I have constructed some HTML and angularJS code to implement the Tinymce editor, but I've encountered a probl ...