AngularJS / Changing the URL only when correspondi

2019-04-11 23:04发布

问题:

Resolve is an interesting property to prevent a template to be displayed regarding some conditional logic dealing with a promise result (solved or rejected).

I use it in my application, here's a conceptual sample:

.config(['$routeProvider', 'securityAuthorizationProvider',
        function ($routeProvider, securityAuthorizationProvider) {
              $routeProvider.when('/test', {
                  templateUrl: '/myCorrespondingView.tpl.html',
                  controller: 'MyCorrespondingCtrl',
                  resolve: securityAuthorizationProvider.requireAuthenticatedUser
              });
        }])

So, this code expects to display /myCorrespondingView.tpl.html content if and only if securityAuthorizationProvider.requireAuthenticatedUser is resolved (promise term).

My expectation is: I don't want to change the URL to http://myApp.com/test if this promise in resolve part is rejected. The reason is simple, I don't want to uselessly reload the previous controller if my rejection logic is to let the user on his current page (thus needing a redirection to this latter) .

Is there an efficient way to achieve this with the resolve property other than shifting the conditional logic at the source, meaning into the previous controller?

回答1:

I was dealing a similar problem some time ago. My solution was to redirect the user to a login page - you can use the page user is coming from - in the authentication provider (in your case it would be securityAuthorizationProvider.requireAuthenticatedUser) if the user wasn't logged in.



回答2:

I know this is an old question, but for all users who are looking for an answer, i will provide my solution.

I have a popup / modal / alert whatever which is displayed over the whole page. in this popup is a history, so you can open a new view and can go back to the old view.
I added a feature that you can go back with your back-button on mouse or browser.

my js:

SYSTEM.run( [ "$rootScope", "Popup", function( $rootScope, Popup ) {
    $rootScope.$on( "$routeChangeStart", function ( e ) {
        if ( $rootScope.popup ) {
            Popup.back();
            e.preventDefault();
            return;
        }
    } );
} );

So what you could do is, get the next route (provided in $routeChangeStart) and check if this url is secured and run your service. if your service is resolved redirect to the url and set the checking variable to true/false, so on the next change you won't check your service again.

Hope that helped.