execute a method encapsulated within a factory from external to AngularJS

Although this question is similar to others posted here, none of the solutions provided have worked for me.

My Cordova/AngularJS/Ionic app currently polls a remote server every 10 minutes to retrieve JSON data, and push notifications are working correctly using the PhoneGap Build plugin. What I am trying to achieve is to integrate the push notifications with the polling mechanism, so that when a notification is received, it triggers the poller to fetch the latest content in between the regular poll intervals.

Here is the existing code that is functioning:

var schoolApp = angular.module('schoolApp', ['ionic',  'schoolApp.controllers', 'schoolApp.services'])

schoolApp.run(function(Poller) {});


.factory('Poller', function($http, $interval,updateContentLocalStorage) {
      var pollerFunct = function() {  
        // fetch and process some JSON from remote server
       } 

    // run on app startup, then every pollTimeout duration 
    setTimeout(function(){ pollerFunct(); }, 10000);
    $interval(pollerFunct, pollTimeout);

}) // END factory Poller

Push notification processing, outside of Angular

// handle GCM notifications for Android
function AndroidOnNotification(e) {
    var $http = angular.element(document.body).injector().get('$http');
    var $state = angular.element(document.body).injector().get('$state');

    // Issue: unable to call pollerFunct() from AndroidOnNotification(e)
    angular.element(document.body).injector().get('Poller').pollerFunct();

}

My goal is to successfully call the pollerFunct() function from within the AndroidOnNotification(e) function without encountering errors such as "processMessage failed: Error: TypeError: undefined is not a function."

Answer №1

After @Petr pointed out that my previous code was returning nothing, I revisited my code and made some adjustments. Here is the updated version that now works:

.factory('Poller', function() {
      var pollerFunct = function() {
        // fetch and process some JSON from remote server
       } 

    // return something
    return { 
          poll: function() {
             pollerFunct();
             return; 
          }
        }   
}) 

This function can be called by:

angular.element(document.body).injector().get('Poller').poll();

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

Proper Functioning of Keydown Event Listener Fails in React/Next.js

I am currently developing an Image Gallery Lightroom component using React/Next.js. The functionality involves clicking on gallery images to open a modal in a react portal. The modal includes a close button and left/right arrow buttons for image navigation ...

I'm having trouble executing the JavaScript function

function contentChange(){ var paragraphs = document.getElementsByTagName("p"); for(var i = 0 ; i < paragraphs.length ; i++){ paragraphs[i].innerHTML = "hello" ;}} contentChange(); I'm struggling to change the content of all ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Creating a Universally Unique Identifier in NextJs

I'm currently experimenting with the following code snippet: import { randomUUID } from 'crypto' var id = randomUUID() within my NextJs application, but unfortunately, I encountered the following error: index.js?46cb:369 Uncaught TypeErro ...

Transferring account information to a function call in the near-js-api

I am attempting to utilize the following method in near-js-api for my contract. It requires a Rust AccountId as input. What is the correct procedure to serialize an Account and send it to the contract? Also, are there any specific considerations when inv ...

Utilizing ngDisabled within ng-class

After reviewing the ui-bootstrap pagination template, I am confused about the use of ngDisabled within ng-class. I would appreciate some clarification on this matter. I examined the 'PaginationController', and it seems that ngDisabled is not a s ...

Managing empty props in React applications

I am facing an issue where I need to display an image fetched from an API on app start, but when I try to render it in React, the application crashes with the error message: TypeError: Cannot read property 'icon' of undefined. Although the icon ...

Achieving responsive masonry layout with Bootstrap 4

I'm attempting to implement the bootstrap 4 masonry effect on my website, but I'm facing issues with card responsiveness. The page is very basic without any special effects. While the page works well when resizing the browser window, it doesn&ap ...

Troubarked by problems NodeJS faces when trying to establish a connection with CosmosDB using a connection

Having trouble with my code that fails when I try to create a new instance of the CosmosClient. The option to create a CosmosClient using a connection string should be straightforward. The environment variable holds the necessary connection string in this ...

How can you prevent specific dates from being selected in an Angular Datepicker?

Is there a way to exclude Monday from the "mat-datepicker" component? I've tried implementing the following code in my class component: dateFilter = (_date: any) =>{ let day = _date.getDay(); console.log(day); return day != 1; ...

How to eliminate an item from an array using index in JavaScript with jQuery

In order to remove a specific array added in an object by index, I would like the functionality where when a user clicks on a button, it removes the corresponding array. Here's what I have in mind: HTML: <button>1</button> <button>2 ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

Is there a way to verify if a user has selected the correct answer in a quiz program?

Here we have code segments in ajax, javascript, html, and an xml file. I'm looking to calculate the total score based on user input to determine if they selected the correct answers for a test. I've attempted to figure this out, but I'm str ...

Issue with Kendo dropdown's optionLabel functionality malfunctioning

Check out the Kendo code snippet below for a dropdown control. I'm currently facing an issue where I am trying to display a "Please select" option in the dropdown. This code works perfectly fine for all other dropdowns except for this specific one. T ...

URLRouterProvider's otherwise state reloads due to empty state parameters of the parent

My state configurations are set up as follows: $stateProvider .state('parentState', { abstract: true, url: '/:tenantId/', param: { tenantId: { array: false } }, ...

The use of async components in Vue.js with named imports

I understand how to dynamically load components asynchronously in Vue. For example, instead of importing MyComponent directly: import MyComponent from '@/components/MyComponent' export default { components: { MyComponent } } We can use ...

What is the best way to fetch multiple values using momentjs from firebase?

After fetching data from Firebase and storing it in an array, I am attempting to retrieve the posted_at values (timestamp of when something was posted) in a time format using Vuejs. However, I am facing difficulty as it only retrieves a single value instea ...

Searching for documents in MongoDB using minimum as a condition in the query

My user base is expansive, each facing a unique set of problems at different times. I am currently searching for users or documents that share a specific problem type (referred to as "top":1) but only among those, I am interested in isolating the entry wit ...

Execute a function on elements that are added dynamically

I'm in the early stages of learning javascript and jquery, so this issue might be very basic. Please bear with me. Currently, I am dynamically adding new link (a) elements to a division with the id "whatever" using the following code: $("#whatever") ...

``From transitioning from Django templating to implementing a full RESTful architecture?

Looking to convert my django/html/css website to a REST (json) structure. Previously reliant on django template rendering for frontend responses. Interested in how to manage url redirection and incorporate json data into html templates without the use of ...