Accessing a factory's functions within itself in Angular

I'm really trying to understand how all of this operates. It seems like it should be working as intended. I have an Auth factory that, when the jwt token expires, calls its 'delegate' method which obtains a new token using the refresh token. However, I keep encountering the error '_this.delegate is not a function'. (I am calling delegate in both cases for testing purposes)

webapp.factory('Auth', function($http, API_URL, $window, $location, jwtHelper ) {
var _this = this;
    var delegate = function(){
        $http.post(API_URL+'/admin/delegate', {refresh_token: $window.sessionStorage.refreshToken } ).success(function(result) {
            $window.sessionStorage.authToken = result.token;
            $window.sessionStorage.refreshToken = result.refresh_token;
            console.log('delegate-result: '+JSON.stringify(result));
            $location.path('/about');
            //LocalService.set('authToken', JSON.stringify(result));
        });
    };
    return {
        //returns true if there is an auth token
        isAuthenticated: function() {
            var storedJwt = $window.sessionStorage.authToken;
            console.log('stored JWT: '+storedJwt);
            var storedPayload = jwtHelper.decodeToken(storedJwt);
            console.log('payload: '+JSON.stringify(storedPayload));
            if(jwtHelper.isTokenExpired(storedJwt)){
                console.log('is expired expired: '+jwtHelper.getTokenExpirationDate(storedJwt));
                _this.delegate();
            } else {
                console.log('is not expired expires: '+jwtHelper.getTokenExpirationDate(storedJwt));
                //For testing
                _this.delegate();
            }
            return $window.sessionStorage.authToken;
            //LocalService.get('authToken');
        },
        delegate: delegate,
        //login function, should be moved to login controller
        login: function(email, password) {
            var login = $http.post(API_URL+'/authenticate', {email: email, password: password } );
            login.success(function(result) {
                console.log('login-result: '+JSON.stringify(result));
                $window.sessionStorage.authToken = result.token;
                $window.sessionStorage.refreshToken = result.refresh_token;
                $location.path('/about');
                //LocalService.set('authToken', JSON.stringify(result));
            });
            return login;
        },

Answer №1

To correct the issue, simply eliminate _this from the line containing _this.delegate().

It's important to note that the function delegate() is accessible within your current scope.

Using var in a factory is acceptable and there is a distinction when it comes to using a service.

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

Conceal the information within a table using angular js and HTML

Just starting out with angular and I have a table that displays angular data directly in the HTML without any controller or model. <table width="98%" border="0" cellspacing="1" cellpadding="2" class="labels" align="center" id="locc"> <tr style ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

retrieve the JSON object corresponding to the specific category

Here is an example of a JSON: [ { "id":1, "name": "BMW E46 PANDEM", "price": 130000, "currency":"USD", "color":"white", "category":"car" }, { "id":2, "name": "Yamaha", "price": 2000, "currency":"USD", "c ...

What are some ways to streamline and improve the readability of my if/else if statement?

I've created a Rock Paper Scissors game that runs in the console. It currently uses multiple if/else if statements to compare user input against the computer's selection and determine a winner. The code is quite lengthy and repetitive, so I' ...

Retrieving the content of input elements within a div post removal

I have a situation where I need to dynamically add input text fields inside a div and then delete the div while retaining the values of the input field in a variable. Here's an example code snippet that demonstrates this: $(document).ready(funct ...

Tips for maximizing the benefits of debounce/throttle and having a truly dynamic experience

Attempting to implement a similar concept in Vue: props(){ debouncing: {type: Number, default: 0} }, methods: { clicked: _.debounce(function() { this.$emit('click'); }, this.debouncing), } Unfortunately, the code breaks when ...

Webpage push notifications are a convenient feature that allows websites to

Is it possible to incorporate web notifications on websites built using JSPs with jQuery, Vue, and Angular.js on the front end? Is there a method to integrate web notifications within this specific environment? ...

Encountering a TypeError message stating that "selector.includes is not a function" while attempting to scrape using cheerio and

Trying my hand at web scraping with the code snippet below: const cheerio = require('cheerio'); const jsonframe = require('jsonframe-cheerio'); const $ = cheerio.load('https://coinmarketcap.com/all/views/all/'); jsonframe($) ...

Component does not support camelCase names

My current challenge involves creating a navbar component where I need to share some data from the main page to the component. After spending several hours researching how to use components, I have been unable to find an explanation as to why camelCase var ...

What do you call a JavaScript function when it has a name

This code is confusing to me. It's not the usual JavaScript syntax for a function that I know of. Is this a specific function? Or perhaps it's a callback for when an update event occurs? Apologies for these beginner questions, as I am quite new t ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

Accessing a JSON file in JavaScript

My website has a script that populates dropdown menus and is currently running from a custom.js file. While it works well, there is one aspect of it that I am not entirely satisfied with. The script involves embedding the various levels of menu, which am ...

Fetching Unicode block specials using axios in getStaticProps with Next.js

Click here to view the code and data results My attempt using the fetch method was successful, but I encountered issues when trying to use 'axios' ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

Altering the color of a Fabulous Icon in real-time

I'm having trouble changing the color of an Awesome Icon with this code I created. Instead of getting the desired color, I am getting 'undefined' as a result. <script type="text/javascript"> function changeAIColor(idName) { alert ...

Looking for assistance with changing the class of a span when a radio button is selected

I'm facing an issue with toggling the class of a <span> when a radio button is clicked. <html> <head></head> <style type="text/css"> .eHide { display:none; } </style> <script type="text/javas ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

The Google Map is not showing all the details

Our app is developed using ReactJS on Rails API, with a Google map integrated. However, when visiting this link and clicking "Map View", some grey space appears under the Google Map. An example image can be found here: example We are having trouble findi ...

Issue with jQuery ajax in Internet Explorer 6

Hey there, I'm dealing with a strange issue: The success handler in my $.ajax call looks like this: function(data){ alert(data); } Seems pretty straightforward, right? The problem I'm facing is that the data sent by the server is ALW ...

What are some ways to style an image that has been added using JavaScript using CSS?

I utilized a JavaScript function to add an image, which looked like this: function show_image(src) { var img = document.createElement("img"); img.src= src; document.body.appendChild(img); } But when I attempt to change its style using CSS: img ...