Is AngularJS Service a Singleton for Your Application?

As a relative newcomer to angularJS, I've learned that services should be singleton, but for some reason it's not working for me. Here is my service:

 .factory('TrainingPlan', function($http, SERVER){

   var o = {
     exercises: [],
     planID : 0
   };

   o.init = function(){
     if(o.exercises.length == 0)
      return o.getAllExercises();
   };

   o.getAllExercises = function(){
     $http({
       method: 'GET',
       url: SERVER.url + 'listener.php?request=getAllExercises&planID=' + o.planID
     }).then(function(data){

       o.exercises = angular.copy(o.exercises.concat(data.data));

       console.log("Exercises in Trainingplan Services");
       console.log(o.exercises);

       return o.exercises;
     })
     ;
   };

   o.getExercise = function(exerciseID){
     for(var i = 0; i < o.exercises.length; i++){
       if(o.exercises[i].exerciseID == exerciseID)
       {
         return o.exercises[i];
       }
     }
   };

  return o;
 })

Additionally, I have two Controllers:

  .controller('TrainingDetailCtrl', function($scope, $stateParams, TrainingPlan, $timeout) {
   TrainingPlan.init();
    $timeout(function(){
      $scope.exercises = TrainingPlan.exercises;
      $scope.numberOfUnfishedExercises = $scope.exercises.length;
      button.innerHTML = "asdf";
    }, 250);
  })

(I haven't pasted the entire controller, but everything seems to be working as expected so far...)

  .controller('TrainingHistoryEditCtrl', function($scope, $stateParams, TrainingPlan, $timeout) {
    var exerciseID = $stateParams.exerciseID;

    $scope.currentExercise = TrainingPlan.getExercise(exerciseID);
    console.log($scope.currentExercise);
  })

Therefore, when transitioning from TrainingDetailCtrl where I have all the exercises of 'TrainingPlan', it seems that when changing sites, TrainingPlan no longer retains the exercises for use in TrainingHistoryEditCtrl.

Answer №1

The reason behind this issue is that your $http function initiates an asynchronous call. This means that even if you call the init function, the result may not have arrived by the time the code reaches the $timeout(function(){.. line.

To see this in action, check out this demonstration on JSFiddle. Notice how the value is empty until after waiting for 10 seconds.

To resolve this issue, consider returning a promise from the factory. Then, inside the controller, utilize the then method to pass in a callback function.

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

Making changes to the res object in an Express.js application

I came up with an innovative idea for the backend design of my single-page application website. My plan is to configure it so that any routes starting with "/api/" will return only the necessary data in JSON format, while all other routes will trigger a fu ...

Choose an option from a dropdown menu using JavaScript

Currently, I am working on a project that involves using javascrypt in conjunction with selenium. While attempting to search for and select an item from a list, I have encountered difficulties in selecting the element even after successfully locating it. I ...

Simply tap on the image to include it in the HTML5 Canvas drawing

Currently, I am in the process of drawing a circle onto my html5 canvas as shown in the code snippet below: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> &l ...

Using getElementsByTagName in E4X code involves querying for specific

Is it possible to retrieve an array of elements in E4X for an unknown tagname, similar to how the DOMs getElementsByTagName function works, within a function? My initial idea was: (function (doc, tag) { return doc..[tag]; }) Can this be achieved? ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

Submitting a form without refreshing the page, displaying the output, reloading the form, and repeating the process. Wash,

There is a form on my page with dynamic drop-down options, an input box, and a submit button. To include this form on my page, I use the following code: <div id="dropdown"> <?php include("./listforward.php"); ?> </div> The listfo ...

javascript conceal other sections upon hovering

There are 4 list items (<li>) that I want to use as triggers for linked images. In this project, I am using vanilla JavaScript as jQuery is not allowed. Below is the code snippet: var children = document.querySelectorAll('#resistorContent > ...

How can I retrieve an updated object array within an extended class in JavaScript?

Hey everyone, I am new to working with ES6 classes. Currently, I am trying to inherit an initialized object (this._obj) with updated data in the class B, but I am encountering an issue where I am getting the length of the initialized object instead of the ...

What is the process of sending data to another JSP page via AJAX when submitting data to a link within a JSP page?

I am facing an issue with forwarding data from a URL link in a JSP form page to another JSP page after submitting the form. How can I achieve this successfully? index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> ...

Guide to downloading Excel file using AngularJS and RESTful API

Code Snippet for Angular JS: $scope.getExcelDownload = function(index,basketid,brokerid,tradeDate,serverid,transid) { var myformid = 'ExcelForm' + index; ExcelDownload.get({brokerid : brokerid,basketName : basketid,appl : &ap ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Can you please tell me the CSS pseudo element that corresponds to the AM/PM field in an <input type="time">

The issue with the am/pm display is dependent on the browser that the app is opened in. I am looking for a universal solution to ensure it does not appear in any popular browsers. Below is the HTML code for my input time field: <input type="time" for ...

A Node.js middleware that logs a message just once

My nodejs express app serves a file that requires and loads css files, js files, etc. I have implemented a logging middleware that retrieves the client's IP address and logs it (after cross-checking with a JSON file containing malicious IPs). Due to t ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

Exploring the Functions and Applications of Headers in Javascript

After completing a project which involved updating a JSON database from the front end, I am still uncertain about the role of the headers within the AxiosConfig. Can you explain the difference between using axios with and without it? For instance: What s ...

Vue search button not returning results

Hello, this is my HTML file. <div id="app1" v-cloak> <input v-model="term" type="search"> <button @click="search">Search</button> <p/> <div v-for="post in posts" class="post"> ...

Add to Firebase reference using AngularFire

Imagine I'm constructing a never-ending scroll of articles. The article's ID is obtained from the URL: var id = $stateParams.id; I aim to startAt that specific index in my Firebase collection and restrict it to 10 items: var limit = 10; var a ...