gpt4 book ai didi

javascript - ui-router deferIntercept 和状态参数

转载 作者:数据小太阳 更新时间:2023-10-29 03:52:58 28 4
gpt4 key购买 nike

我使用 ui-router 的新 deferIntercept() 来更新浏览器 url 而无需重新加载我的 Controller :

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

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

当用户单击后退按钮或手动更改 URL 时,更新 Controller 中的 $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();

来源: official documentation for $urlRouterdeferIntercept 方法提供代码示例。它将对 $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();
});

关于javascript - ui-router deferIntercept 和状态参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530322/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com