В предыдущих версиях angularFire можно было обеспечить выделение выбранных маршрутов с помощью «authRequired» и «pathTo» с помощью метода маршрутизации Angular $ routeProvider. Они больше не работают с AngularFire 0.6.0. Каков эквивалентный параметр/метод в Angular 0.6.0?Как обеспечить маршрут в AngularFire 0.6.0 (authRequired)?
1
A
ответ
2
Маршрутизация была перемещена из углового огня по тем же причинам, что и ее вытащили из ядра Углового - чтобы быть менее самоуверенным в том, как проводится маршрутизация и какую библиотеку вы должны использовать.
Вы по-прежнему можете включить маршрутизацию, захватив module from angularFire-seed, который готов к подключению к игре.
Шагов:
- добавить ngRoute и routeSecurity ваших зависимостей приложений
- декларировали loginRedirectPath постоянной
- добавить
authRequired
в соответствующих случаях
Пример:
// add routeSecurity to your dependency libs
angular.module('myApp', [..., 'ngRoute', 'firebase', 'routeSecurity']);
// declare the loginRedirectPath variable
angular.module('myApp').constant('loginRedirectPath', '/login')
// put authRequired in your routes
$routeProvider.when('/account', {
authRequired: true, // must authenticate before viewing this page
templateUrl: 'partials/account.html',
controller: 'AccountCtrl'
});
// live long and prosper
Вот скопируйте модуль с 0.6.0 для соответствия политике SO; обратитесь непосредственно к источнику для текущей версии:
(function(angular) {
angular.module('routeSecurity', [])
.run(['$injector', '$location', '$rootScope', 'loginRedirectPath', function($injector, $location, $rootScope, loginRedirectPath) {
if($injector.has('$route')) {
new RouteSecurityManager($location, $rootScope, $injector.get('$route'), loginRedirectPath);
}
}]);
function RouteSecurityManager($location, $rootScope, $route, path) {
this._route = $route;
this._location = $location;
this._rootScope = $rootScope;
this._loginPath = path;
this._redirectTo = null;
this._authenticated = !!($rootScope.auth && $rootScope.auth.user);
this._init();
}
RouteSecurityManager.prototype = {
_init: function() {
var self = this;
this._checkCurrent();
// Set up a handler for all future route changes, so we can check
// if authentication is required.
self._rootScope.$on("$routeChangeStart", function(e, next) {
self._authRequiredRedirect(next, self._loginPath);
});
self._rootScope.$on('$firebaseSimpleLogin:login', angular.bind(this, this._login));
self._rootScope.$on('$firebaseSimpleLogin:logout', angular.bind(this, this._logout));
self._rootScope.$on('$firebaseSimpleLogin:error', angular.bind(this, this._error));
},
_checkCurrent: function() {
// Check if the current page requires authentication.
if (this._route.current) {
this._authRequiredRedirect(this._route.current, this._loginPath);
}
},
_login: function() {
this._authenticated = true;
if(this._redirectTo) {
this._redirect(this._redirectTo);
this._redirectTo = null;
}
else if(this._location.path() === this._loginPath) {
this._location.replace();
this._location.path('/');
}
},
_logout: function() {
this._authenticated = false;
this._checkCurrent();
},
_error: function() {
if(!this._rootScope.auth || !this._rootScope.auth.user) {
this._authenticated = false;
}
this._checkCurrent();
},
_redirect: function(path) {
this._location.replace();
this._location.path(path);
},
// A function to check whether the current path requires authentication,
// and if so, whether a redirect to a login page is needed.
_authRequiredRedirect: function(route, path) {
if (route.authRequired && !this._authenticated){
if (route.pathTo === undefined) {
this._redirectTo = this._location.path();
} else {
this._redirectTo = route.pathTo === path ? "/" : route.pathTo;
}
this._redirect(path);
}
else if(this._authenticated && this._location.path() === this._loginPath) {
this._redirect('/');
}
}
};
})(angular);
Смежные вопросы
- 1. Сохранить и получить $ приоритет элемента в коллекции AngularFire Firebase 0.6.0
- 2. Локальная стратегия Passport.js, как обеспечить маршрут
- 3. Как обеспечить маршрут для текущего пользователя в REST API?
- 4. Как обеспечить текущий маршрут или просмотреть макет в ExpressJS?
- 5. Как обеспечить безопасный маршрут в магистрали и Express?
- 6. AngularFire 0,5 $ на «загружен» не стрелять правильно
- 7. Что такое $ angularfire?
- 8. MVC3 Маршруты - как обеспечить маршрут с определенным значением имеет приоритет?
- 9. Как установить приоритет в Angularfire
- 10. Как bindTo() работает в AngularFire?
- 11. Как развернуть метеор 0.6.0 + to heroku
- 12. AngularFire - Как установить фильтр?
- 13. Как сделать каскадное удаление в Angularfire?
- 14. Meteor 0.6.0 и Collection API
- 15. ARF-анализ в ELKI 0.6.5 или 0.6.0
- 16. Объекты AngularFire
- 17. вернуть $ добавить исх из Firebase пункта AngularFire
- 18. Несколько коллекций в AngularFire?
- 19. Невозможно использовать маршрутизатор в щ angularFire семечек репо
- 20. Использование .numChildren() в AngularFire
- 21. Если http.path установлено, есть ли способ, чтобы обеспечить маршрут/
- 22. angularfire $ waitForSignIn() использование?
- 23. Не работает примеры из учебника angularfire
- 24. Как перебирать наблюдаемый список AngularFire?
- 25. AngularFire: как запускать запросы присоединения
- 26. Как работает функция AngularFire $ save?
- 27. Firebase angularfire как обновить элемент
- 28. Как получить текущий маршрут/маршрут в Синатре?
- 29. Извлечение данных Firebase в обратном вызове AngularFire
- 30. Как запросить данные из ссылок в AngularFire