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

Tips for displaying axios status on a designated button using a spinner

Utilizing a v-for loop to showcase a list of products retrieved from an API request. Within the product card, there are three buttons, one for adding items to the cart with a shopping-cart icon. I aim for the shopping-cart icon to transform into a spinner ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

When using React / Next.js, the .map() function may not rerender the output based on changes in the state array if the keys remain the same

In my react component, Matches.js, I handle the display of tournament matches sorted by rounds. The data is fetched from a parent component through nextjs SSR and passed as props to the child component. To avoid unnecessary requests upon data changes like ...

Incorporate a hanging indent within the text enclosed by the <li> element

(revised multiple times to enhance clarity) Disclaimer: I did not create the HTML code. Below is the structure of the HTML (please note that the links and text following them are on the same line): <li> <strong>Heading of section</str ...

What is the best way to delete a particular CSS class using jquery?

My task is to remove the "btn" class from items that have an additional argument in their class name, such as: <input type="button" class="btn btn-mini btn-success email-user" id="emailid5" value="Email Tester"> I specifically need to only remove t ...

Extracting the call from REST API in JSON format

Working with a third-party database using a REST API, I encountered an error response (as expected). Here is the code snippet: transaction.commit(function(err) { if (err){ var par = JSON.parse(err); \\ leading to error: SyntaxError: Unexpecte ...

What is the process of extracting data from JavaScript output using Mongoose?

Currently facing an issue with mongoose while working on a blog website and integrating quilljs. The problem arises from the output file in my JavaScript file that contains the configurations for my quill editor. var quill = new Quill('#editor&ap ...

Concentrate on what comes next

Within my JavaScript code, I have the following line: $('input')[$('input').index(this)+9].focus(); I intended for this line to focus on the next element. However, when it executes, I encounter the following error: Error: [$rootSc ...

Is there a navigation feature in VueJS that functions similarly to React Router?

I am currently working on enhancing the navigation experience of an existing vueJS application that utilizes Vue Router. When working with React, I typically structure breadcrumbs in the following manner: <Breadcrumbs> <Route path="/users&q ...

Navigate to a specific section on a different page while excluding a distance of X

I've implemented the script below to execute the action mentioned in the title. <script type="text/javascript"> var jump=function(e) { if (e){ e.preventDefault(); var target = $(this).a ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

Error encountered in my application due to Node.js (Error [ERR_HTTP_HEADERS_SENT]: Unable to change headers once they have been sent to the client)

Experiencing an error message in my application when typing nodeJS. Please assist. , Encountering an error after sending the first POST request while running the app. const express = require('express') const Workout = require("../models/work ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

Can you provide some straightforward instances of single-axis zooming using d3?

I'm interested in creating a single-axis zoom for d3's zoom behavior. Are there any straightforward examples that demonstrate how to achieve this? I came across Mike Bostock's example, but I found it a bit complex to grasp. Here is the code ...

Using a string to access a property within a ReactJS object

I am looking to simplify my React Component by referencing a JS object property using a string. This will allow me to remove repetitive conditional statements from my current render function: render() { const { USD, GBP, EUR } = this.props.bpi; ...

Eliminate repeated entries in a drop-down menu and display them with commas in between

I am working with a list that contains various language combinations: German to English German to Spanish German to Chinese German to French English to Spanish English to French English to Greek English to Portuguese Does anyone have suggestions on how ...

Unexpected Issues with the Ant Design Sidebar Layout Demo

My React webapp is utilizing the Ant design component framework version 4. I attempted to integrate this example from the Antd documentation into my webapp: https://codesandbox.io/s/ymspt However, when I implemented the code in my webapp, the result didn ...