Never miss out on the broadcast!

I am working on an Angular Project and I am trying to create an Authentication mechanism. Here is the code for my Login controller:

angular.module('authModule')
.controller('LoginCtrl', function($rootScope, $location, loginRESTService, UserService){
    var login = this;

    function signIn(user) {
        loginRESTService.login(user)
            .then(function(response) {
                console.log(response);
                user.access_token = response.user_id;
                UserService.setCurrentUser(user);
                $rootScope.$broadcast('authorized');
                $location.path("/formList");
            });
    }
})

In addition, I have a main controller with some methods:

angular.module('authModule')
.controller('MainCtrl', function ($rootScope, $state, LoginService, UserService) {
    var main = this;

    $rootScope.$on('authorized', function() {
        console.log("ENTRE CON PERMISO");
        main.currentUser = UserService.getCurrentUser();
    });

    $rootScope.$on('unauthorized', function() {
        console.log("ENTRE SIN PERMISO");
        main.currentUser = UserService.setCurrentUser(null);
        $state.go('login');
    });   
})         

The issue here is that 'authorized' and 'unauthorized' events are never being triggered, and I'm not sure why.

This is my app.js file:

angular
  .module('pysFormWebApp', [
    ...
    'translateModule',
    'formModule',
    'authModule'
  ])
  .config(function ($routeProvider,  $httpProvider) {
    $routeProvider  
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })    
      .when('/login', {
        templateUrl: 'views/auth/login.html',
        controller: 'LoginCtrl',
        controllerAs: 'login'
      }) 
      .otherwise({
        redirectTo: '/'
      });      

Here is a snippet of my index.html file (it's quite long so I'll just include a part of it):


    <div ng-controller="MainCtrl as main" >
        <button ng-if="main.currentUser" class="btn btn-default navbar-btn" ng-click="main.logout()">Logout <strong>{{main.currentUser.name}}</strong> 
        </button>
    </div>

Answer №1

One thing to consider is that the 'unauthorized' event may not be properly broadcasted in your code, which could explain why $rootScope.on('unauthorized') isn't functioning as expected.

Additionally, it's possible that the main controller is being executed before the login controller, causing it to miss the event altogether.

Feel free to give this a try and see if it helps resolve your issue.

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

"Troubleshooting: State array in ReactJS/NextJS not rendering correctly following setState

I am facing challenges with rendering my objects using .map() within React / NextJS. Within my code, I have a function where I retrieve images from Firebase Cloud Storage as shown below: getImages = () => { let firebase = loadFirebase() ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Transforming JSON data into a dynamic Tableview

I've been experimenting with this issue for quite some time now, but I can't seem to find a solution. My API returns tasks in JSON format. When I print the data using Ti.API.info(this.responseText), it looks like this: [INFO] [{"created_at":"20 ...

Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them. Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle. The script looks like thi ...

Guide on handling asynchronous data return within a reducer

I'm struggling to properly handle the state when receiving data from the back-end of my application. This is the code I have: if (action.type === actionTypes.getList) { const id = action.payload.userId; Axios.post(`${apiUrl}/lists`, { ...

What is the quickest way to display data immediately after submitting a form using ajax?

Is there a way to display data instantly after submitting a form via AJAX and saving it through a controller function? I want to be able to view the saved data on the same page without having to refresh it: <span class=" store_comment_like " data-com ...

Disable button with Checkbox Javascript functionality

In my PHP code, I have an array of users that I pass to the view (in Laravel) and use a foreach loop to display all users in a table. Everything is working fine so far. However, I want to make a "send" button visible when a checkbox is clicked, instead of ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Looking for assistance in retrieving a document by its reference id from Firestore using ReactJS?

As a newcomer to using firestore and reactjs, I am currently working on creating a basic react code that retrieves documents from 2 different collections. The two collections I am focusing on are: user-habits {email, habitid} habits {habitid, conte ...

Is it possible to omit certain columns when extracting data from a Kendo grid?

My challenge involves extracting data from a Kendo grid using the following JavaScript call: var data = JSON.stringify($(".k-grid").data("kendoGrid").dataSource.data()) This retrieves all properties in the C# class for the records. There are three proper ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

Executing a secondary function only once after a repeated condition has been met

Functionality: The secondary function is triggered when the initial condition is met and satisfied. This means that if the condition is true, the secondary function will be executed. However, the secondary function should only be triggered once until the ...

"Ensure div remains at the bottom of the page even while

In order to implement a feature where the menu sticks to the top when scrolling down, you can use the following JS code. You can view a live example of this functionality on this Plunker by widening the preview window to see the columns side by side. wi ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

What is the best way to incorporate a JavaScript function into an Angular 2 template?

I need a slider for my project and I am using AdminLTE <input type="text" value="" class="slider form-control" data-slider-min="-200" data-slider-max="200" data-slider-step="5" data-slider-orientation="horizontal" data-slider-sele ...

Sharing data between controllers in distinct pages with distinct ng-app directives in AngularJS

I have searched through numerous questions on stack overflow regarding this issue. Unfortunately, none of the solutions provided seem to be effective in my case. My dilemma involves two HTML pages: AddUser.html and ListUser.html. Both pages utilize the sa ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

What could be causing the onClick event handler to trigger twice in my create-react-app?

Does anyone know why the "upvote" onClick handler is triggering twice? Even though the logs show it's only running once, the score increases by 2 export default class Container extends Component { constructor(props) { super(props); this.sta ...

Is it possible for AngularJS to share a service among multiple ng-apps?

I've been working on developing a web app that involves multiple Angular ng-apps, and I want to use the same service code for at least two of them (even though they don't share data but perform similar functions). How can I prevent code duplicati ...