我正在使用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全局并根据它更改视图.
最佳答案 它很难调试,因为我现在没有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事件,该事件在连接/断开设备时触发.您的应用程序现在应该在每次触发事件时自动更改状态.