Display specific template on $routeChangeError
Asked Answered
E

3

1

I have a feeling there is no way to do this, but I figured it couldn't hurt to ask. I'm using route.resolve to check the current user status when routes change and determine if they are authorized for that route. Assuming they aren't, ideally I'd like to simple display an error template rather than change routes to point to an error page.

Obviously the latter is more straightforward but it doesn't feel right. Is it possible to handle it this way or will have to get more creative here.

One solution I've considered is to have directives in the root template that show based on an $rooteScope.errorState is set. Not my favourite solution but a workable one for the time being.

Exhilarate answered 3/1, 2014 at 0:40 Comment(0)
T
1

ng-route doesn't natively support that, you could make it work but it requires some effort. However, you can use http://angular-route-segment.com/.

It enhances ng-route with resolveFailed option so you can define a new set of controller and template to use when resolver fails.

Tryptophan answered 3/1, 2014 at 0:46 Comment(2)
Yeah I was wondering if ui-router might support this situation too. Just checking this out and it seems like it's pretty good. Cheers!Exhilarate
@ChrisNicola might be, I didn't try ui-route before. angular-route-segment.com uses ng-route internally, and ui-route use its own mechanism.Tryptophan
E
1

This is the solution I ended up with which uses just the core ngRoute module. A custom directive might make this a bit cleaner but this does work.

  $rootScope.$on '$routeChangeStart', (e, route) ->
    $rootScope.errorTemplateUrl = null

  $rootScope.$on '$routeChangeError', (e, c, p, error) ->
    $rootScope.errorTemplateUrl = views['errors/' + error]

In my project views[] is a list of shortcut names to templates. In this case I can pass something like views['errors/404'] however you can get the error template url any way you like. Then in my base view I have.

<div ng-if="!errorTemplateUrl" ng-view></div>
<div ng-if="errorTemplateUrl" ng-include="errorTemplateUrl"></div>

If resolves fail I can reject and pass the name of the error template that I would like to display to this which then displays it appropriately.

Exhilarate answered 10/7, 2014 at 21:11 Comment(0)
S
0

edit: misunderstood question

in your resolver, when access denied is detected, call this

$templateCache.put('template.html', 'Access Denied');

and then resolve the route as successful. Where template.html is the location of your templateUrl.

Skat answered 3/1, 2014 at 0:51 Comment(1)
Right but the objective here was to not change the route path, but just display the error.Exhilarate

© 2022 - 2024 — McMap. All rights reserved.