Display specific template on $routeChangeError

送分小仙女□ 提交于 2019-12-13 17:14:32

问题


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.


回答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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/20894568/display-specific-template-on-routechangeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!