更改 ui-view 模板而不更改 URL [英] Change ui-view template without changing URL

查看:25
本文介绍了更改 ui-view 模板而不更改 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下状态配置(简化):

I have the following states configuration (simplified):

$stateProvider
  .state(
    'showitem', 
     { url: '/item/{id}', templateUrl: 'showitem.html', controller: 'MyCtrl' }
  )
  .state(
    'notFound',
    { url: '^*path', templateUrl: '404.html'}
  );

当我输入 /badurl 时,404 错误按预期显示.

When I enter /badurl, 404 error is shown as expected.

当我输入 /item/123 时,应用程序的 API 正在查询具有指定标识符的项目.如果无法找到该项目,它会返回成功的项目数据或 404 HTTP 标头.为了全局检测此类错误,我写了一个http拦截器:

When I enter /item/123, the application's API is being queried for item with specified identifier. It returns item data on success or 404 HTTP header if the item could not be found. In order to detect such errors globally, I wrote a http interceptor:

$httpProvider.interceptors.push(function($q, $location) {
  return {
    responseError: function(rejection) {
      if(rejection.status == 404)
        $location.path('/404');
      return $q.reject(rejection);
    }
  };
});

代码有效,但当项目的 id 错误时,/item/123 URL 更改为 /404,显示错误页面.

Code works but when the item's id is wrong, the /item/123 URL changes to /404 which shows an error page.

问题是 - 如何将 404.html 视图加载到我的 <div ui-view></div> 元素中没有 更改网址?

Question is - how to load the 404.html view into my <div ui-view></div> element without changing the URL?

有一个类似的问题但 templateProvider 没有似乎没有解决我的问题.

There is a similar question but the templateProvider does not seem to address my problem.

推荐答案

this answer 和 @RadimKohler 评论启发的解决方案.从 notFound 路由中删除 url:

Solution inspired by this answer and @RadimKohler comment. Remove url from notFound route:

$stateProvider
.state(
  'showitem', 
  { url: '/item/{id}', templateUrl: 'showitem.html', controller: 'MyCtrl' }
)
.state(
  'notFound',
  { templateUrl: '404.html'}
);

配置其他规则:

$urlRouterProvider.otherwise(function($injector, $location) {
  var $state = $injector.get('$state');
  $state.go('notFound');
  return $location.path();
});

最后,在 404 API 错误时转到 notFound 路由:

And finally, go to the notFound route on 404 API error:

$httpProvider.interceptors.push(function($q, $injector) {
  return {
    responseError: function(rejection) {
      if(rejection.status == 404)
        $injector.get('$state').go('notFound');
      return $q.reject(rejection);
    }
  };
});

这篇关于更改 ui-view 模板而不更改 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆