Handle unknown routes in Angular by showing Page Not Found error

This commit is contained in:
Arik Fraimovich
2018-02-08 09:31:58 +02:00
parent 69b3ea4715
commit d6eb8f436f
2 changed files with 19 additions and 3 deletions

View File

@@ -44,17 +44,21 @@ class AppViewComponent {
$rootScope.$on('$routeChangeStart', (event, route) => {
this.handler.reset();
if (route.$$route.authenticated) {
// In case we're handling $routeProvider.otherwise call, there will be no
// $$route.
const $$route = route.$$route || { authenticated: true };
if ($$route.authenticated) {
// For routes that need authentication, check if session is already
// loaded, and load it if not.
logger('Requested authenticated route: ', route);
if (Auth.isAuthenticated()) {
this.applyLayout(route.$$route);
this.applyLayout($$route);
} else {
event.preventDefault();
// Auth.requireSession resolves only if session loaded
Auth.requireSession().then(() => {
this.applyLayout(route.$$route);
this.applyLayout($$route);
$route.reload();
});
}

View File

@@ -103,6 +103,18 @@ function registerPages() {
});
});
});
ngModule.config(($routeProvider) => {
$routeProvider.otherwise({
resolve: {
// Ugly hack to show 404 when hitting an unknown route.
error: () => {
const error = { status: 404 };
throw error;
},
},
});
});
}
function registerFilters() {