路由的Resolve机制(需要了解promise)
angular的resovle机制,实际上是应用了promise,在进入特定的路由之前给我们一个做预处理的机会
1、在进入这个路由之前先懒加载对应的 .js
1 $stateProvider 2 .state('owner_detail_room',{ 3 url: '/owner_detail_room/{id:[0-9]{1,10}}', 4 views:{ 5 'main' : { 6 templateUrl:function() { return 'templates/owner_detail_room.html'}, 7 controller: 'owner_detail_roomCtrl' 8 } 9 }, 10 resolve:{ 11 loadCtrl: ['$ocLazyLoad', function($ocLazyLoad){ 12 return $ocLazyLoad.load('js/owner_detail_roomCtrl.js') 13 }] 14 } 15 })
2、请注意,resolve是一个对象,它的key由我们自己指定,value则是一个promise的异步请求或字符串
首先,来一个多个键值对的例子1-懒加载js,2-获取user,3-判断页面权限
1 .state('owner_detail_room',{ 2 url: '/owner_detail_room/{id:[0-9]{1,10}}', 3 views:{ 4 'main' : { 5 templateUrl:function() { return 'templates/owner_detail_room.html'}, 6 controller: 'owner_detail_roomCtrl' 7 } 8 }, 9 resolve:{ 10 loadCtrl: ['$ocLazyLoad', function($ocLazyLoad){ 11 return $ocLazyLoad.load('js/owner_detail_roomCtrl.js') 12 }], 13 user: ['userservice',function(userservice){ 14 return userservice.getUser(); 15 }], 16 userLevelCheck:['LevelCheck','userservice',function(LevelCheck,userservice){ 17 var isPass = LevelCheck.check(userservice.userLevel); 18 if(isPass){ 19 return userservice.userLevel; 20 }else{ 21 $state.go('level-is-not-enough'); 22 } 23 }] 24 } 25 })
然后在对应的页面的ctrl中,可以注入resolve中的返回
1 app.controller('owner_detail_roomCtrl',['$scope','user', function($scope,users) { 2 $scope.users = users; 3 });
3、从resolve到进入路由Ctrl中,应用到的就是promise,($q服务属性方法:$q.defer(), $q.all(), $q.when(), $q.reject(), $q.resolve().....)
来个栗子,剩下看大家了,
1 resolve: { 2 data: function(User, Post, $q) { 3 deferred = $q.defer(); 4 5 $q.all([User.getAll, Post.getTops()]).then(function(results) { 6 deferred.resolve({ 7 users: results[0], 8 posts: results[1] 9 }) 10 }); 11 12 return deferred.promise; 13 } 14 }
最后的最后,如果有错误,请务必,一定要指出