I can't figure out why I'm receiving a TypeError stating that onSuccess is not a function within my AngularJS service

Utilizing an angularjs service that utilizes restangular for API calls.


angular.module('app.userService', [])
    .factory('userService', ['localStorageService', '$rootScope', 'Restangular',
        function(localStorageService, $rootScope, Restangular) {
            function checkIfLoggedIn() {
                return localStorage.getItem('token');
            }

            function login(email, password, onSuccess, onError) {
                Restangular.all('api/authenticate')
                    .post({
                        email: email,
                        password: password
                    })
                    .then(
                        function(response) {
                            localStorage.setItem('token', response.token);
                            onSuccess(response);
                        },
                        function(response) {
                            onError(response);
                        });
            }

            function logout() {
                localStorageService.remove('token');
            }

            function getCurrentToken() {
                return localStorage.getItem('token');
            }

            function getAuthenticatedUser(onSuccess, onError) {
                Restangular.one('api/authenticated_user?token=' + getCurrentToken()).get().then(function(response) {
                    onSuccess(response.user);
                }, function(response) {
                    onError(response);
                });
            }
            Restangular.setDefaultHeaders({
                'Authorization': 'Bearer ' + getCurrentToken()
            });
            return {
                checkIfLoggedIn: checkIfLoggedIn,
                login: login,
                logout: logout,
                getCurrentToken: getCurrentToken,
                getAuthenticatedUser: getAuthenticatedUser
            };
        }
    ]);

Encountering a TypeError when calling userSvc.getAuthenticatedUser() in a controller: "onSuccess is not a function" This is how the call is made:

 console.log(userSvc.getAuthenticatedUser());

Seeking assistance with resolving this issue. Using angular 1.6.

Answer №1

It's normal to encounter errors when your service method expects callback methods to be passed.

function getAuthenticatedUser(onSuccess, onError){
}

Make sure to include the necessary callback methods when calling the function:

userSvc.getAuthenticatedUser(function() {}, function() {})

Alternatively, you can verify if the argument is defined and is a function according to AngularJS documentation.

function getAuthenticatedUser(onSuccess, onError) {
    Restangular.one('api/authenticated_user?token=' + getCurrentToken()).get().then(function (response) {
        !!onSuccess && angular.isFunction(onSuccess) && onSuccess(response.user);
    }, function (response) {
        !!onError && angular.isFunction(onError) &&
        onError(response);
    });
}

Answer №2

When using the getAuthenticatedUser() function, it is important to pass a callback function as the first argument. This is necessary because there is no built-in check within the function to see if the onSuccess parameter has been provided. The same goes for the onError callback, so both arguments must be included.

To avoid potential errors, you can either add a check within the getAuthenticatedUser function to ensure the callbacks are present (e.g. onSuccess && onSuccess()), or simply provide empty anonymous functions as placeholders.

userSvc.getAuthenticatedUser(function() {}, 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

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

My Fullcalendar is displaying events for the upcoming month. How can I resolve this issue?

This is the start date for my event in the full calendar: start: new Date('2016', '02', '07', 00, 30) However, when loading the calendar, this event is displaying on March 7, 2016. How can I resolve this issue? ...

Husky and lint-staged failing to run on Windows due to 'command not found' error

I'm facing issues with getting husky and lint-staged to function properly on my Windows 10 system. Here's how my setup looks like: .huskyrc.json { "hooks": { "pre-commit": "lint-staged" } } .lintstagedrc ( ...

The initial call to the method results in an undefined return value

In my code, there is a function that retrieves distinct values from a database. Here's how it looks: function getUniqueCategories(res, req) { query = `SELECT DISTINCT name FROM product_category;`; connection.query(query, function (err, rows) { ...

Ensuring the correctness of environment variables in Next.js using Zod

After spending the entire day trying to figure it out, I realize that the solution may be simpler than expected. I am currently using the well-known zod library to validate my environment variables and transform data. However, I keep encountering a persis ...

Can you explain the significance of npm WARN excluding symbolic link?

Could you please explain the meaning of npm WARN excluding symbolic link? Also, any advice on how to resolve this issue? ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Ways to transmit information from a React application to a Node server

As a Nodejs beginner, I am using the rtsp-relay library for live streaming. Currently, it is working in the frontend when the URL is included in the server proxy object like this: rtsp://.....@..../Stream/Channel/10. However, I want users to be able to inp ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

Tips for concealing the Bottom bar action in React Native

Currently facing an issue with React Native - I need to hide the bottom action bar located just below my tab bar navigation. I'm trying to create a clone of the Disney + App and this particular problem has me stuck: Here's the bottom part of my ...

Ways to bypass mongoose schema validation while making an update request in the API

In my model, one of the fields is specified as providerID: { type: Number, required: true, unique: true }. The providerID is a unique number that is assigned when inserting provider details for the first time. There are situations where I need to update ...

Having trouble getting my AngularJS animations to work, hitting a roadblock

Here is the code I've put together for you to review, with no official purpose in mind. I just saved this code to use at a later time. <script> var apps = angular.module('myApp', ['ngAnimate']); //header apps.cont ...

Swapping React Components with a Click of a Button

My webpage features a button labeled "Sign Up". Once this button is clicked, I want it to display a new component named "SignUp" in place of the original button. Currently, my method involves using setState to trigger the rendering of the new component upo ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Angular blocking interface version 0.2.2 encountered a problem with the error message "Unable to access property 'blockUI' of null"

I'm facing an issue with the Angular block UI version 0.2.2 that I added. It's not functioning properly and showing the following error: Cannot read property 'blockUI' of null Error displayed in console: Code snippet: sampleclick( ...

Combining the power of Angular.js and Require.js

As I develop a local app on nw.js using angular.js, I'm starting to question my approach. In my controller, I often find myself writing code like this: .controller('UserSettingsCtrl', function($scope, $mdDialog, $translate) { var fs = ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

Is it possible to utilize various return values generated by a regex?

Working on a project where I am utilizing regex to extract links from a Google Calendar XML feed. The links appear in the following format: <a href="http://www.drsketchysdublin.com/event-registration/?ee=11">http://www.drsketchysdublin.com/event-reg ...

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

Angular 1.4.8 Issue: [$injector:modulerr]

I can't seem to identify the main cause of this error. I consistently see a green underline below the word angular in my javascript file. I'm not sure why. (Using Visual Studio Code) HTML <html ng-app="myapp"> <head> ...