ui-router deferIntercept和state params

Sim*_*iau 9 javascript angularjs angular-ui-router

我使用ui-router的新deferIntercept()更新浏览器URL而不重新加载我的控制器:

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

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

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

谢谢 !

Tyl*_*ich 7

您的呼叫$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();
Run Code Online (Sandbox Code Playgroud)

源:官方文件$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();
});
Run Code Online (Sandbox Code Playgroud)