Using AngularJS `$state.go` to navigate without redirection in ExpressJS

I'm facing a strange issue with my ExpressJS setup for serving AngularApp Files locally. I have a main controller with the following code snippet:

else{
            console.log('Forwarding to Login');
            $state.go('signin', {});
            console.log($state.$current);
}

Even though this code is being called, nothing happens and the current state remains empty.

Interestingly, setting up nginx locally and directing the root path to my project's folder resolves the issue.

So, what could be causing ExpressJS to fail in redirecting and loading the controller when using $state.go? It works fine with ui-sref...

This is my express.js configuration:

var express = require('express'); var app = express();

app.use('/libs', express.static(__dirname + '/libs')); app.use('/assets', express.static(__dirname + '/assets')); app.use('/app', express.static(__dirname + '/app'));

app.set('port', process.env.PORT || 3000);

app.all('/*', function(req, res, next) {
    res.sendFile('index.html', { root: __dirname }); });

var server = app.listen(3000, function () {

 var host = server.address().address;  var port = server.address().port;

 console.log('X is listening at http://%s:%s', host, port);

});

And here are my defined states:

$stateProvider
        // Dashboard
        .state('dashboard', {
            url: "/dashboard",
            templateUrl: "/app/components/dashboard/dashboard.view.html", 
            data: {pageTitle: 'Home', pageSubTitle: 'MyTitle Workspace'},
            resolve: {
                deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                    return $ocLazyLoad.load({
                        name: 'MyApp',
                        insertBefore: '#ng_load_plugins_before',
                        files: [
                        ]
                    });
                }]
            }
        })
        // Login
        .state('signin', {
            url: '/signin',
            templateUrl: '/app/components/login/login.view.html',
            data: {pageTitle: 'Sign in', pageSubTitle: ''},
            controller: 'LoginController',
            controllerAs: 'loginCtrl',
            resolve: {
                deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                    return $ocLazyLoad.load({
                        name: 'MyApp',
                        insertBefore: '#ng_load_plugins_before', 
                        files: [
                            '/app/shared/authentication/login.controller.js'
                            ]
                    });
                }]
            }
        })

Your insights would be greatly appreciated :)

Best regards, Patrick

Answer №1

If you're unsure about the layout of your route, I suggest including the following code in your .run:

app.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, next) {
        /* Triggered before any route change */
    });

    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        /* This will execute on every successful route change */
    });

    /*
    Logs an error message to console if a route change fails
    */
    $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
        console.log('state change error - ' + error + ' - to: ' + angular.toJson(toState) + ' params: ' + angular.toJson(toParams) + '\nfrom: ' + angular.toJson(fromState) + ' params: ' + angular.toJson(fromParams));
    });
});

By implementing this code, you'll have better insights into the process. Plus, you can address any issues directly within these blocks.

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

Engaging with Firebase's oauth sign outs feature

I'm struggling with logging users out automatically from Firebase after they sign out of their Google account. My app relies on $signInWithPopup, so I need a way for Firebase to also log them out when they sign out of Google. I initially thought Angu ...

Guide on modifying an angular-material directive and compiling it

When I compile a native HTML element, everything works perfectly fine. However, when I try to compile an Angular Material element (md-button), the console displays an error message: "Error: [ngTransclude:orphan]". I've reached a point where I am com ...

Looping through an array in Angular with ng-repeat

In my controller, I have managed to loop through the primary xml-based data successfully. However, I am facing challenges in passing the secondary child data (in the second level tr tag where I want all "list" categories to repeat) within the loop. angula ...

What is the trick to shortening paragraphs with dots...?

There is a p tag, <p> most iconic character in cinema</p> I need to truncate the text after 8 characters, and display dots afterwards. For example: most ic... Is there a way to achieve this using CSS? Any help with AngularJS would also be ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

Having trouble dynamically assigning the ng-model attribute

I am trying to populate the ArrayINeed array, which is the object I need to pass back to the API call. Currently, I am getting undefined for "ConfirmedTrackingReferenceNumbers": Dc.ArrayINeed. Despite researching various posts online and on SO, I have been ...

Guide to using MongoDB with Express

Why is books.insertOne inserting a null value instead of tmpId, even though console.log(tmpId) displays the correct value? How can this issue be resolved? app.post('/logged/:login/addBook/confirm', urlencodedParser, function(req,res){ var lo ...

Is it considered poor form for an Angular controller to invoke a function on a directive?

My custom Angular directive functions as a unique combobox, where clicking on the input control reveals a div below it with a list of items from a model object. The user can type text into the input control to filter the displayed list. In addition to the ...

Structural engineering for massive webpage

Currently I am in the process of building a large page using AngularJS. As I plan out the architecture for this page, I am debating which approach would be most effective. The page consists of 3 distinct blocks with various functionalities, but the prima ...

I keep encountering an issue with Nodemailer where it keeps throwing the error message "TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument needs to be a string or.."

The error message is incredibly long, but here is a brief excerpt: TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object at PassThrough.Writable.write ( ...

Using Angular.js to update the `ng-model` with the value of text.textContent

There is a javascript event that dynamically updates the value of an input var posx = event.target.querySelector('input.posx'); posx.value = event.dx; This code successfully updates the html: <input type="text" ng-model="posx" si ...

Create the next app with updated files by rebuilding it while utilizing express as the server

I'm currently utilizing the combination of Next.js and Express.js in my project. In this setup, Express handles all the routing tasks instead of Next.js. For a smoother development experience, I require a process where whenever a file is modified, Ne ...

Enabling NodeJS and Express to manage Cache-Control headers

I have a nodeJS server set up to provide resources through a REST API. Recently, one of the consumers of the API started including this in the header: "Cache-Control": "no-cache" This caused Node to reject the preflight options request with an error mess ...

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

Transmit and receive information between Javascript and Node.js through Express framework

Currently, I am utilizing the Express platform along with the Twilio Node.js SMS API and JavaScript to send text messages to my users. However, I am facing an issue in sending data through GET variables on the front-end and capturing those values with node ...

What is the most effective way to display a success notification?

After updating the data in my application, I want to display a success message. Although the Success function is functioning correctly, the message itself is not appearing. When I click on the save() button, a small alert box pops up but the message fails ...

Having trouble accessing environment variable in NodeJS with ExpressJS

In my Express.js project, I have set a variable like this: app.set('HOST', 'demo.sample.com');. However, when I try to access this variable, I am getting undefined as the result. I am trying to retrieve the value using process.env.HOST. ...

Guide to creating an ES6 express application using webpack 2 and babel

In my .babelrc file, I have only included the es2015 preset and I am using a Webpack 2 configuration for my project. I want to create an express app in ES6. Here is the webpack configuration: const path = require('path'); module.exports = { t ...

If a particular class is present on an element

Is it feasible to set an ng-if directive to true based on the presence of a specific class in an element? For example: <div class="edge" ng-repeat="item in items"> <div ui-view ng-if="(ng-repeat div has class of edge)" ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...