AngularJS子页面刷新父页面时丢失ID参数的正确reload调用方法
Hey there, I see you're running into an issue where reloading a parent state with $state.reload() is dropping your ID parameter—resulting in a URL like Entity/account/Details/ instead of the expected Entity/account/Details/224563. Let's break down how to fix this:
What's Going Wrong
First, let's look at your state config: your URL is /Entity/:entity/Details/:id?ids, which means this state requires two mandatory parameters: entity and id. When you called reload earlier, you only passed the id parameter, leaving out entity. UI-Router needs all required params to build the full URL properly, so missing entity was causing it to drop the ID too. Also, there's a possible typo in your code (personstate instead of accountstate) that might have been messing things up.
The Correct Way to Call $state.reload()
You need to pass all required state parameters when reloading, not just the ID. Here's how to do it properly:
// Get the state instance from the injector var accountState = $myapp.findOverviewInjector().get("$state"); // Build a params object with ALL required values var reloadParams = { entity: accountState.params.entity, // Grab the existing entity from current state params id: parseInt($state.params.entityId) // Your target ID }; // Reload the current state with the complete params accountState.reload(accountState.current, reloadParams);
If you want a more concise approach, you can merge the current state params with your updated ID to avoid missing any values:
var accountState = $myapp.findOverviewInjector().get("$state"); var updatedParams = angular.extend({}, accountState.params, { id: parseInt($state.params.entityId) }); accountState.reload(accountState.current, updatedParams);
Why Your Previous Attempts Didn't Work
- Incomplete Params: By only passing
id, you didn't provide theentityparameter that your state's URL requires. UI-Router couldn't resolve the full route, so it dropped the ID as well. - $state.go vs $state.reload: You mentioned
$state.godidn't meet your needs—and that makes sense.$state.gotriggers full route navigation hooks, while$state.reload()directly reloads the current state (and its children) without re-triggering the entire navigation flow. That's why you need to stick withreload().
Quick Checks to Avoid Future Issues
- Double-check your state's
entityparam: You haveparams:{entity:"Acount"}in your config—if that's a typo for"Account", fix it to match your expected URL. - Verify
$state.params.entityIdis valid: Add aconsole.log($state.params.entityId)to make sure it's actually returning the ID you expect before parsing it.
内容的提问来源于stack exchange,提问作者BilalMr

