An error of TypeError is being encountered in AngularJS

Hello, I am new to creating mobile apps with Ionic and Angular. Currently, I have a simple login form and a corresponding login button that triggers a controller. Here is the code snippet for the controller:

angular.module('starter.controllers', [])
    .controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state) {
        $scope.data = {};

        $scope.login = function() {
            LoginService.loginUser($scope.data.username, $scope.data.password)
                .success(function(data) {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Login HERE!',
                        template: 'HERE: your credentials!'
                    });
                }).error(function(data) {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Login failed!',
                        template: 'Please check your credentials!'
                    });
                });
        }
    });

The above controller calls a service defined as follows:

angular.module('starter.services', [])
    .service('LoginService', function($http,$q) {
        return {
            loginUser : function(name, pw) {
                // Service implementation details here
            }
        }
    })

I am successfully building and calling a RESTful API using the correct URL. Upon successful login, I receive a token ID as a string. In case of failure, I get an error message also as a single line.

After some research, I found out that a GET request expects an array of data while in my controller.js file, there's a variable declared as a String. The main issue I'm facing is that the .success method inside the controller is expecting an array instead of a String.

If anyone has suggestions on how to convert the response to an array or if it's possible to handle a single string response, please advise. Thank you!

UPDATE:

Below is the exception stack trace I encountered:

08-17 11:08:56.412: E/Web Console(6538): TypeError: Object #<Object> has no method 'success'
08-17 11:08:56.412: E/Web Console(6538):     at Scope.$scope.login (file:///android_asset/www/js/controllers.js:36:12)
08-17 11:08:56.412: E/Web Console(6538):     at $parseFunctionCall (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:21172:18)
08-17 11:08:56.412: E/Web Console(6538):     at IonicModule.config.factory.element.onclick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:53674:9)
08-17 11:08:56.412: E/Web Console(6538):     at Scope.$get.Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:23228:28)

Answer №1

Your approach to handling promises seems overly complex in my opinion. It's not clear what you intend to achieve with all those success and error functions. Simplifying it, you can just include:

angular.module('starter.services', [])
.service('LoginService', function($http,$q) {
    return {
        loginUser : function(name, pw) {
            console.log('username=' + name + ', password=' + pw);

            var url = 'https://myURL/myapi/authenticate?username=' + name + '&password=' + pw;
            console.log('url=' + url);

            return $http.get(url);
        }
    }
})

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

You've got a function floating around without any specific theme tied to it. Make sure one of the parent elements is utilizing a ThemeProvider for proper context

I am working on implementing a Navbar in my current Project. The dependencies I am using are: mui/icons-material: ^5.2.5 mui/material: ^5.2.6 mui/styles: ^5.2.3 Here is the folder structure of my project: Root.jsx Navbar.jsx styles ...

Tips for adjusting div content to fit a fixed height on all devices

Looking to adjust the size of the #left-content div based on the height of the window, while ensuring that all content is visible within the fixed #left-bg. However, when viewing on mobile or tablet devices, the content appears hidden. .left-bg{ backgro ...

Activate the search feature in select2 to allow multiple selections

I'm looking for a way to incorporate a search box into my multi-select fields using select2. Oddly enough, while the search boxes show up as expected in single-select fields, applying the same select2() function to a multi-select field doesn't s ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

How can I display an array of data with a changing name using a FlatList in React Native?

How can I render a list of array data with a dynamic name in a FlatList using React Native? Below is the list of data that I would like to display in the FlatList: const movies = [ { '4W2JJ0CLbvfLJzBUHORVaz6sAGv2': [ { name: ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

The Hover Hover textbox stays in place once clicked on

I have implemented a search bar that displays a textbox when a user hovers over a button. I am looking to modify the code so that the textbox remains visible even after the user has clicked on it. This way, if the user accidentally moves their mouse away f ...

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

Obtaining JSON information with Svelte

I'm currently facing a mental block. My goal is to fetch JSON data using the Youtube API. The error message I am encountering is "Cannot read property 'getJSON' of undefined". Here's the code snippet I have provided: <script> ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...

Choosing various choices using AngularJS

My goal seems simple using vanilla JS, but with AngularJS, I'm looking for the best way to achieve it within the framework. I aim to update the selected options in a multiple select box without adding or removing any options. Below is a snippet of my ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Is it possible to save a JavaScript interval in a jQuery element's data property?

In the process of developing a jQuery plugin, specifically a jQuery UI widget known as Smooth Div Scroll, I encountered an issue where I needed to store references to intervals that were unique to each instance of the plugin on a page. If I simply declared ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

JQuery and PHP: Saving a rearranged set of divs in a form

Although I've searched for similar questions, none seem to address my specific issue. My problem involves a form with divs generated from a JSON array saved in a separate file. To style the form, I'm using Bootstrap and implementing JQueryUI&apo ...

Calculating the duration between two dates using momentjs and the angular-bootstrap Datepicker

I have integrated 2 Datepickers from angular-bootstrap. Using moment.js for calculating the difference between these Dates. By default, there is a 20-hour difference between the Dates when starting the App, and this calculation works correctly. However, I ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

"Exploring the functionalities of jquery .change() specifically in the

I have a jQuery change function set up to adjust the values of another select drop down whenever the user changes the month (to display the correct number of days). Everything works perfectly in most browsers, but Firefox seems to be giving me trouble :( ...