$ routeProvider async not working

I am creating a chrome app with a USB device. In my main app.js, I want to always check when a device is added / removed and change the URL.

angular.module('rfApp', [
    'ngRoute',
    'ngMaterial',
    'rfApp.view1',
    'rfApp.view2',
    'rfApp.device_not_found'
]).config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
    $locationProvider.hashPrefix('!');

    function checkForDevices() {
        RFFWHID.getDevices(function(current_devices) {
            if(current_devices.length > 0) {
                $routeProvider.otherwise({redirectTo: '/view1'});
            } else {
                $routeProvider.otherwise({redirectTo: '/device_not_found'});
            }
        });
    }

    chrome.hid.onDeviceAdded.addListener(function(){
        checkForDevices();
    });
    chrome.hid.onDeviceRemoved.addListener(function(){
        checkForDevices();
    });

    checkForDevices();

}]);

But redirection does not work in async function.

Edit:

I found a similar question. How to call $ urlRouterProvider.otherwise () after loading a JSON file? , and the first answer describes that this is not possible. But how can I solve this problem. I need to check that usb remove / add globally and change views based on this.

+4
source share
1 answer

, Chrome, . $routeProvider $routeChangeSuccess:

angular.module('rfApp')
.factory('deviceManager', ($rootScope) => {
    let deviceConnected = false;
    
    chrome.hid.onDeviceAdded.addListener(function() {
        checkForDevices();
    });
    chrome.hid.onDeviceRemoved.addListener(function() {
        checkForDevices();
    });

    checkForDevices();
    return {
        isDeviceConnected: isDeviceConnected
    };

    function isDeviceConnected() {
        return deviceConnected;
    }

    function checkForDevices() {
        RFFWHID.getDevices(function(current_devices) {            
            deviceConnected = current_devices.length > 0;
            $rootScope.$emit('deviceChange');
        });
    }    
})
.run(($rootScope, $location, deviceManager) => {
    $rootScope.$on('$routeChangeSuccess', checkAndRedirect);
    $rootScope.$on('deviceChange', checkAndRedirect);

    function checkAndRedirect() {
        if (deviceManager.isDeviceConnected()) {
            $location.url('/view1')
        } else {
            $location.url('/device_not_found');
        }
    }
});
Hide result

, , , , , $location.url , .

. $rootScope, , /. .

+1

Source: https://habr.com/ru/post/1667064/


All Articles