AngularJS / Changing the URL only when corresponding template's resolve property is solved

∥☆過路亽.° 提交于 2019-12-06 07:49:36

问题


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.



来源:https://stackoverflow.com/questions/19653666/angularjs-changing-the-url-only-when-corresponding-templates-resolve-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!