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

The dropdown selection for redirecting to a URL is malfunctioning within a PHP while loop

<?php $sql = "select * from letter where societyn='" . $_SESSION['socityname'] ."' "; $result = mysql_query($sql); $i=1; while($row=mysql_fetch_array($result)){ ?> <?php $id = $row['id']; ...

Having trouble accessing properties within a JavaScript object array in React.js?

I have a React.js component that fetches its initial state data from an API call in the componentDidMount(). This data comprises an array of objects. While I can see the entire array and individual elements using JSON.stringify (for debugging purposes), a ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

Inject Angularjs Controller into Module Once DOM is Initialized: Tips and Tricks

When injecting new DOM elements with a controller, I encountered the following issue: app.controller('cart', function ($scope, $http) { $scope.content = { label: "hello, world!", }; }); var $html = '<div ng-controller="c ...

Send the form to the webpage and display various div elements based on the entered information

I have created a form that is designed to display one of four hidden divs on a page, depending on the input provided. Here is the form: <form> <input id="place" name="place" type="text"> <input name="datepicker" type="text" id="datepicker" ...

Is there a way to deliberately trigger an error using Selenium WebDriverIO?

Is there a way to trigger an error using ChromeDriver with Selenium WebDriverIO? I'm not sure if there's a method like browser.fire('error'). ...

Troubles arise when hovering over and connecting endpoints in jsPlumb

I'm currently facing two challenges with my project. Follow this link for more details. 1) The hover effect is working perfectly on the endpoints, but I can't seem to change the colors of my connector when hovering over it. Any suggestions? (Ref ...

Bootstrap datetimepicker is not showing the calendar for selecting a date, making it impossible to choose a specific date

I am facing an issue with integrating the bootstrap datetimepicker with Datatables to filter the data based on selected dates. The problem is that only an input bar is displayed on the page, and there is no calendar or calendar symbol visible. I suspect it ...

Converting yard values to meter values using AngularJS: A comprehensive guide

My task is to convert meter values to yard using two dropdowns. The first dropdown contains various values, while the second dropdown has "meter" and "yard" options. If "meter" is selected in the second dropdown, the values in the first dropdown remain unc ...

Tips on showing a response in an HTML node with Node.js and AngularJS

Just starting out with NodeJS and AngularJS. My goal is to fetch a response from an external site and display it in Angular JS. I managed to send the request and receive a response, but on the UI JSON appears as a string with forward slashes "\". For ...

How to ensure unique results when using DFS for Combination Sum?

I am currently tackling the challenge of solving LeetCode #49 Combination Sum. The objective here is to identify all the distinct combinations that add up to the specified target. While it's relatively straightforward to find permutations that result ...

What is the best way to extract data from the JSON response obtained from the Facebook Graph API in a Node

I am struggling to parse a JSON file in order to extract specific data, particularly the latest picture. How can I achieve this using Node.js and the Facebook Graph API? Below is the snippet of code I currently have: var params = { hostname: ' ...

Issue encountered while constructing an array within the component data following the 'created' event

It's been a while since I've dealt with Vue.Js, so my memory is a bit fuzzy. I'm facing an issue where I can't seem to modify a data array within a function that is called in the created hook. My goal is to create a multidimensional ar ...

Step-by-step guide on generating a fluid list with Express and HTML

Looking to create a dynamic list by fetching data from a JSON file. I want the list items to redirect me to specific content based on their IDs when clicked. However, my current approach is not working as expected, and the list needs to be truly dynamic. ...

Whenever I navigate to this specific route, I consistently encounter an error message in my console

VM28353:1 Error: Unexpected token 'o' found in JSON at position 1 at JSON.parse (<anonymous>) at getUser (auth.js?c7d4:11) at wrappedGetter (vuex.esm-browser.js?5502:335) at Object.eval [as getUser] (vuex.esm-browser.js?5502 ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

What reasons could be preventing the state from updating correctly in Vuex?

Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems ...

What is the process for transmitting a base64-encoded image from AngularJS to Laravel using the POST method?

Hey there! I am a beginner in Laravel and AngularJS. I have a question about sending an uploaded image (converted to base64) to Laravel. This is how my HTML code looks: <input type="file" class="upload upload-button" fileinput="fileinput" filep ...

Receiving the latest global variable in JavaScript using jQuery

I keep receiving undefined type for: $(".ui-slider-handle").attr("title", '"'+current+'"'); Even though I can successfully alert the updated value of current on line 29, it seems to not be working with .at ...