问题
Goal / Expected
Rebuild the state of the app if the user directly goes to a link like this: http://localhost:8080/app/#!/tag_id=5&ticker=GOOG
Results
The app currently still redirects back to /login
via $urlRouterProvider.otherwise('/login');
In my app I am storing the $state
(ui-router) variables in a cookie using ngCookies
.
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
const shareUrl = () => {
// const base = 'https://www.tickertags.com/dashboard/#/';
const base = 'http://localhost:8080/app/#!/';
const cookie = $cookies.get('stateCookie');
console.log('state vars', $httpParamSerializer(JSON.parse(cookie)));
const parsedState = $httpParamSerializer(JSON.parse(cookie));
return `${base}${parsedState}`;
};
// console.log('state.current.name', $state.current.name)
const stateCookie = $cookies.get('stateCookie');
$cookies.putObject('stateCookie', $state.params);
console.log('shareUrl', shareUrl());
})
When changing states:
The log 'state var' will log: state vars tag_id=5&ticker=GOOG
And the log 'shareUrl' will log: http://localhost:8080/app/#!/tag_id=5&ticker=GOOG
I'm trying to just print the $location.search() results of that link first. Below I put a new log in the $stateChangeStart
eventListener.
.run(['$rootScope', '$location', '$state', '$cookies', '$httpParamSerializer',
function($rootScope, $location, $state, $cookies, $httpParamSerializer) {
$rootScope.$on("$stateChangeError", console.log.bind(console));
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams, options) {
const searchObject = $location.search();
console.log('searchObject', searchObject);
});
Results
I got redirected back to the login, which is expected right now. However my searchObject is still empty?
Note I also put a break point on the first line inside of the .run
. The debugger stopped there and I tried to log out $location.search()
while the URL was correct, but it still printed out an empty object...
When I just log out $location
however I do see all of this:
Where to I placed that const searchObject = $location.search();
line so I can correctly capture the pasted URL, then created new params to run a $state.go
on to rebuild the state?
回答1:
Just figured it out!
I needed to add ?
after dashboard:
const base = 'http://localhost:8080/app/#!/dashboard?';
And now it will work:
来源:https://stackoverflow.com/questions/43121888/where-to-capture-the-location-search-vars-in-the-run-statement-in-order-to-r