The Angular controller fails to execute upon startup in the Ionic app

As a newbie to the Ionic Mobile Framework and Angular JS, I'm working on a login page for the first time. My goal is to navigate to the homepage only if the session has not expired when the login page launches. If the session has expired, then it should redirect back to the login page. The functionality works smoothly as I transition between the songs screen/state and the login screen/state. However, I'm facing an issue.

Upon app startup, it directly goes to the songs state or "home" page without executing the controller code for that state. In the controller code, I make a request to our website to check the active session status. If the session is still active, JSON data is returned; otherwise, my authInterceptor handles the transition to the login state.

The main problem lies in the fact that the controller doesn't run during app initialization, and despite extensive searching online, I haven't been able to identify the root cause. Below is a snippet of the code:

.run(function($ionicPlatform, $cordovaSplashscreen, localstorage, $state) {

  setTimeout(function() {
    $cordovaSplashscreen.hide()
  }, 1500)

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }

    if(localstorage.get('subdomain') == undefined || 
      localstorage.get('subdomain') == 'null' || 
      localstorage.get('subdomain') == null ||
      localstorage.get('subdomain') == 'undefined' ||
      localstorage.get('subdomain') == "")
    {
      $state.go('subdomain');
    }
    else
      $state.go('songs');

  });
})  



.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
  $urlRouterProvider.otherwise("/songs");

  $stateProvider
    .state('login', {
      url: "/login",
      templateUrl: "templates/login.html",
      controller: 'LoginCtrl'
    })
    .state('subdomain', {
      url: "/subdomain",
      templateUrl: "templates/subdomain.html",
      controller: 'SubdomainCtrl'
    })
    .state('songs', {
      url: "/songs",
      templateUrl: "templates/songs.html",
      controller: 'SongsCtrl'
    })

  $httpProvider.interceptors.push('authInterceptor');

});

// register the interceptor as a service
.factory('authInterceptor', function($q, $injector) {
  return {
    // optional method
   'responseError': function(rejection) {
      if(rejection.status == 0 || rejection.status == 403){
        $injector.get('$state').transitionTo('login',null,{ reload: true, inherit: true, notify: true });
        if(rejection.config.url.indexOf('login') > -1){
          navigator.notification.alert("Invalid username or password.", function(){}, "Login Failed");
        }
      }

      return $q.reject(rejection);
    }
  };
})

.controller('SongsCtrl', function($scope, $state, user) {

  user.check(); //Resource that hits route on server

  $scope.logout = function()
  {
    user.logout();
    $state.go('login');
  }
})

I appreciate your help. James

Answer №1

The problem stemmed from both an erroneous server response that the interceptor failed to process correctly, along with a malfunctioning debugging tool that hindered my ability to confirm if the controller initiated on startup.

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

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

Guide to switching a button using JavaScript

I am trying to create a button that will toggle the font size between 16px and 14px when clicked. The button text should also change from "Increase Font" to "Decrease Font" accordingly. UPDATE: I managed to get it working, but it only toggles twice and th ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

Learn how to create an animated refreshing icon in React when clicked

I have a refresh icon in my React app that utilizes Material UI. I want the icon to spin for a second after it is clicked, but I am unsure of how to achieve this. Despite attempting some solutions, none have been successful. const useStyles = makeStyles(( ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

Integrate JQuery-Ui into an Angular 7 application using an external .js file

I'm currently working on an Angular 7 project and facing some challenges while trying to integrate the JQuery-Ui plugin. I have successfully installed both JQuery and the plugin, and added them to the scripts array in my angular.json file. Even though ...

Issues with Bootstrap Table Column Widths not Adjusting Properly

I am facing an issue with my Bootstrap 4 table where the fixed column widths specified in the header row are not being respected when the table is rendered. The Time column, for example, should only be 5% of the width but it is taking up more space than ex ...

Line of cubes - tap on a single cube and the others gracefully slide away from view

I am working on a project where I need to create a row of blocks. The goal is for the blocks to slide off the screen when one is clicked, leaving the clicked block in the first position. For instance: https://i.sstatic.net/IB5LI.jpg I attempted using jQ ...

The React component continuously refreshes whenever the screen is resized or a different tab is opened

I've encountered a bizarre issue on my portfolio site where a diagonal circle is generated every few seconds. The problem arises when I minimize the window or switch tabs, and upon returning, multiple circles populate the screen simultaneously. This b ...

Prevent mouse over scrolling for every <select> element on a webpage using JQuery

My code seems to be having some issues. Can you help me figure out what's wrong? <script type="text/javascript" language="javascript"> //trying to disable scrolling on mouse over of <select> elements $(document).ready(function() { ...

What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning? var d = new D ...

Service Worker error - Received redirected response when RedirectMode is not set to "follow"

Browser: Firefox 58.0.2 (64-bit) I am attempting to create a very basic service worker to store content for offline viewing, following the guidelines provided here and here. After installing the service worker successfully upon loading the page for the f ...

What are the steps to implement an Express Error handling middleware in my specific scenario?

I have implemented a router middleware to validate requests and a global Error handler middleware in the server.js file to handle all errors. However, I am encountering an issue within the router while trying to implement this logic. The problem is highli ...

Using Node.js, Express.js, and Redis.io for efficient order processing

Currently, I am working on a project that involves Node.js with express.js and redis.io as the database. I have implemented a get resource with query parameters to retrieve the IDs of libraries containing a specific book. However, I am struggling to unders ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

Guide on smoothly transitioning between 2 points within a requestAnimationframe iteration

Would it be possible to acquire a library for this task, or does anyone have any suggestions for my psuedocode API? Inquiry: How can I create a function that accepts 4 parameters interpolate(start, end, time, ease) and smoothly transition between the sta ...

What is the best way to assign a value to a button in Ionic/Angular?

Is there a way to bind the name and value attributes to a button? I am facing an issue with this and need a solution. I am attempting to achieve the following: <ion-button type="submit" color="primary" style="text-align:center& ...