简体   繁体   English

加载模板文件时处理AngularJS错误

[英]Handle AngularJS errors while loading template file

I create an app with requirement of template files being in two folders - first is available without restrictions and second is available only for logged in users. 我创建了一个应用程序,其中要求模板文件位于两个文件夹中-第一个可无限制使用,第二个仅可用于登录用户。

Things are complicating when somebody refresh the page and session expire before. 当有人刷新页面并且会话在此之前过期时,事情变得更加复杂。 Angular throws error (eg 401) in console while loading template file which I want to avoid. 加载要避免的模板文件时,Angular在控制台中引发错误(例如401)。 Is there a way to catch that event and access response status to for eg redirect the page? 有没有办法捕获该事件并访问响应状态,例如重定向页面?

For your case, we can catch the error and redirect to a page with the help of $location.url() . 对于您的情况,我们可以捕获错误并借助$location.url()重定向到页面。 Here is the concept. 这是概念。 Now i have a controller and in that, i have success function and error function. 现在我有一个控制器,在其中,我有成功功能和错误功能。 Whenever we get an error, the error function will run and we can pass the link of the page you want to redirect. 每当我们收到错误消息时,错误函数就会运行,我们可以传递您要重定向的页面的链接。

$http.get(url,[params])
     .success(function(data, status, headers, config){
    // bind your data to scope
      })
     .error(function(data, status, headers, config) {
        $location.url('/404');
      });

By the use of $routeProvider , you can configure the function something like this : 通过使用$routeProvider ,您可以配置如下功能:

$routeProvider
   .when('/404', {
       templateUrl: '404.html',
       controller: 'yourcontroller'
});

And you can see the description for $location.url() here 您可以在此处查看$ location.url()的描述

Hope it works 希望能奏效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM