ui路由器deferIntercept和状态参数

ui-router deferIntercept and state params

本文关键字:状态 参数 deferIntercept 路由器 ui      更新时间:2023-09-26

我使用ui路由器的新deferIntercept()来更新浏览器url,而不需要重新加载我的控制器:

$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
  e.preventDefault();
  if ($state.current.name !== 'search') {
    $urlRouter.sync();
  }
  $urlRouter.listen();
});

使用此代码,单击浏览器的后退按钮会将URL更改为上一个,但我无法更新控制器状态以反映此更改。$stateParams仍然包含用户首次加载页面时设置的值。

当用户单击后退按钮或手动更改URL时,更新控制器内的$state和$stateParams对象的最佳方法是什么?

谢谢!

$urlRouter.listen()的调用应该放在事件处理程序之外。您提供的代码片段应更改为:

$rootScope.$on('$locationChangeSuccess', function(e, newUrl, oldUrl) {
  e.preventDefault();
  if ($state.current.name !== 'search') {
    $urlRouter.sync();
  }
});
// Moved out of listener function
$urlRouter.listen();

来源:$urlRouter的官方文档提供了deferIntercept方法的代码示例。它将对$urlRouter.listen()的调用置于侦听器函数之外:

var app = angular.module('app', ['ui.router.router']);
app.config(function ($urlRouterProvider) {
  // Prevent $urlRouter from automatically intercepting URL changes;
  // this allows you to configure custom behavior in between
  // location changes and route synchronization:
  $urlRouterProvider.deferIntercept();
}).run(function ($rootScope, $urlRouter, UserService) {
  $rootScope.$on('$locationChangeSuccess', function(e) {
    // UserService is an example service for managing user state
    if (UserService.isLoggedIn()) return;
    // Prevent $urlRouter's default handler from firing
    e.preventDefault();
    UserService.handleLogin().then(function() {
      // Once the user has logged in, sync the current URL
      // to the router:
      $urlRouter.sync();
    });
  });
  // Configures $urlRouter's listener *after* your custom listener
  $urlRouter.listen();
});