codememo

Angular ui-router $state.go가 내부 확인으로 리디렉션되지 않습니다.

tipmemo 2023. 10. 15. 17:24
반응형

Angular ui-router $state.go가 내부 확인으로 리디렉션되지 않습니다.

나의 angularjs 앱에서, 나는 사용자가 랜딩 페이지에 착륙하고 이미 인증되었는지 확인하고 있고, 그를 홈 페이지로 리디렉션하고 있습니다.

.state('landingpage', {
            abstract: "true",
            url: "/landingpage",
            templateUrl: "app/landingpage/landingpage.html",
            resolve: {
                AutoLoginCheck: ['$state', '$window', function ($state, $window) {

                    if($window.localStorage.access_token != null)
                    {
                        if($window.sessionStorage.access_token == null) {
                            $window.sessionStorage.access_token = $window.localStorage.access_token;
                        }
                        UserInfoService.SetUserAuthenticated(true);

                        // it is not redirecting
                        return $state.go('app.home');

                    }
                }]
            }
        })

문제는 모든 해결 코드가 성공적으로 실행되었지만 사용자가 app.home으로 리디렉션되지 않는다는 것입니다.왜 이런 일이 일어나는지 누가 말해줄 수 있나요?

참고: 'app' 상태는 'app'에 표시할 데이터를 가져오는 분해능도 있습니다.본국의

.state('landingpage', {
            abstract: "true",
            url: "/landingpage",
            templateUrl: "app/landingpage/landingpage.html",
            resolve: {
                AutoLoginCheck: ['$state','$window', '$q','$timeout', function ($state, $window,$q,$timeout) {

                    if($window.localStorage.access_token != null)
                    {
                        if($window.sessionStorage.access_token == null) {
                            $window.sessionStorage.access_token = $window.localStorage.access_token;
                        }
                        UserInfoService.SetUserAuthenticated(true);


                        $timeout(function() {
                           $state.go('app.home')
                        },0);
                        return $q.reject()

                    }
                }]
            }
        })

이 정도면 괜찮으실 겁니다.

당신의 문제에 두가지 해결책이 있을 수 있습니다.

  • 먼저 이벤트를 내보내고 청취자가 상태 전환을 처리합니다.리스너를 부모 컨트롤러의 어느 곳에서나 구현할 수 있습니다.

  • 두 번째로 $state를 구현할 수 있습니다.Start hook을 변경하고 거기서 리디렉션 상태를 확인합니다.

    $rootScope.$on('$stateChangeStart', function (event, toState) {      
         if (toState.name === 'landingpage') {              
           if (!isAuthenticated()) { // Check if user allowed to transition                  
                event.preventDefault();   // Prevent migration to default state                  
                $state.go('home.dashboard');           
            }
          }
    });
    

사용가능$location.url('/')대신.

확인을 사용하여 컨트롤러에 상태에 맞는 컨텐츠나 데이터를 제공할 수 있습니다.resolve는 컨트롤러에 주입해야 하는 종속성 맵(선택 사항)입니다.

AuthState를 확인하고 그에 따라 리디렉션하는 컨트롤러를 가질 수 있습니다.

     .state('landingpage', {
        abstract: "true",
        url: "/landingpage",
        templateUrl: "app/landingpage/landingpage.html",
        resolve: {
            AutoLoginCheck: ['$window', function ($window) {

                if($window.localStorage.access_token != null)
                {
                    if($window.sessionStorage.access_token == null) {
                        $window.sessionStorage.access_token = $window.localStorage.access_token;
                    }

                   //assuming userInfoService does the authentication
                    var isAuthenticated = userInfoService.SetUserAuthenticated(true);
                    return isAuthenticated;

                }
            }]
        },
        controller: ['$state','AutoLoginCheck', function($state, AutoLoginCheck){
          if(AutoLoginCheck){
            //authenticated
            $state.go('app.home');
          } else {
            //redirect to unauthenticated page
            $state.go('....');
          }
        }]
    })

이 스레드는 오래된 스레드이지만 $location.path()를 사용하여 state.resolve() 블록 내부에서 리디렉션을 수행합니다.

어쨌든 약속 상태를 기다리는 것을 해결합니다.당신이 할 수 있는 가장 좋은 것은 약속을 돌려주고 당신의 상태에 시간 초과를 추가하는 것입니다.

resolve: {
    AutoLoginCheck: ['$state', '$window', '$timeout', '$q', function ($state, $window, $timeout, $q) {
        var deferred = $q.defer();
        if(user.isLogin()){
             deferred.resolve();
        }else{
          $timeout(function(){
            $state.go('app.home');
          }
          deferred.reject();
        }
        return deferred.promise;
    }]

언급URL : https://stackoverflow.com/questions/29080128/angular-ui-router-state-go-is-not-redirecting-inside-resolve

반응형