$ routeProvider async无法正常工作

时间:2017-01-17 20:10:57

标签: javascript angularjs

我正在使用USB设备构建Chrome应用程序。在我的主app.js中,我想要检查何时添加/删除设备并更改网址。

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();

}]);

但是重定向不能在异步函数中工作。

修改

我发现了类似的问题How to call $urlRouterProvider.otherwise() after loading JSON file?,第一个答案描述了这是不可能的。但我怎么能解决这个问题。我需要检查usb remove / add全局并根据它更改视图。

1 个答案:

答案 0 :(得分:1)

由于我现在没有Chrome应用程序的环境,因此很难调试,但您可以改变方法。您可以使用$ routeChangeSuccess:

,而不是使用$ routeProvider重定向



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');
        }
    }
});




所以基本上每次状态发生变化时,都会检查设备是否以同步方式连接,并且您可以使用$location.url或最适合您的方式重定向用户。

编辑:我添加了一个自定义的$ rootScope事件,该事件在设备连接/断开时触发。您的应用程序现在应该在每次触发事件时自动更改状态。

相关问题