Programing

각도-UI 라우터가 이전 상태를 얻습니다.

lottogame 2020. 6. 12. 22:05
반응형

각도-UI 라우터가 이전 상태를 얻습니다.


현재 상태의 이전 상태를 얻는 방법이 있습니까?

예를 들어 이전 상태가 현재 상태 B 이전의 상태 (이전 상태는 상태 A였던)를 알고 싶습니다.

ui-router github doc 페이지에서 찾을 수 없습니다.


ui-router는 이전 상태가 전환되면 추적하지 않지만 상태가 변경 될 때 이벤트 $stateChangeSuccess가 브로드 캐스트 $rootScope됩니다.

해당 이벤트에서 이전 상태를 잡을 수 있어야합니다 ( from탈퇴 상태).

$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
   //assign the "from" parameter to something
});

새 상태로 이동하기 전에 resolve를 사용하여 현재 상태 데이터를 저장합니다.

angular.module('MyModule')
.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('mystate', {
            templateUrl: 'mytemplate.html',
            controller: ["PreviousState", function (PreviousState) {
                if (PreviousState.Name == "mystate") {
                    // ...
                }
            }],
            resolve: {
                PreviousState: ["$state", function ($state) {
                    var currentStateData = {
                        Name: $state.current.name,
                        Params: $state.params,
                        URL: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        });
}]);

가독성을 위해 내 솔루션 (stu.salsbury의 답변을 기반으로 함)을 여기에 배치합니다.

이 코드를 앱의 추상 템플릿에 추가하여 모든 페이지에서 실행되도록하십시오.

$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from, fromParams) {
    $rootScope.previousState = from.name;
    $rootScope.currentState = to.name;
    console.log('Previous state:'+$rootScope.previousState)
    console.log('Current state:'+$rootScope.currentState)
});

rootScope의 변경 사항을 추적합니다. 꽤 편리합니다.


다음 예제 decorator에서 (구성 단계에서 앱당 한 번만 실행)을 만들고 $state서비스에 추가 속성을 추가 하므로이 방법은 전역 변수를 추가 $rootscope하지 않고 다른 서비스에 추가 종속성을 추가 할 필요가 없습니다 $state.

내 예에서는 사용자가 이미 로그인했을 때와 로그인 후 이전의 "보호 된"페이지로 리디렉션하지 않을 때 사용자를 색인 페이지로 리디렉션해야했습니다.

내가 사용하는 알려지지 않은 유일한 서비스는 다음 authenticationFactoryappSettings같습니다.

  • authenticationFactory사용자 로그인 만 관리하면됩니다. 이 경우 사용자가 로그인했는지 여부를 식별하는 방법 만 사용합니다.
  • appSettings어디서나 문자열을 사용하지 않는 상수입니다. appSettings.states.loginappSettings.states.register로그인에 대한 국가의 이름을 포함하고 URL을 등록합니다.

그런 다음 controller/ serviceetc로 $state서비스 를 주입해야 하며 다음과 같이 현재 및 이전 URL에 액세스 할 수 있습니다.

  • 흐름: $state.current.name
  • 이전: $state.previous.route.name

Chrome 콘솔에서 :

var injector = angular.element(document.body).injector();
var $state = injector.get("$state");
$state.current.name;
$state.previous.route.name;

이행:

(와를 사용 angular-ui-router v0.2.17하고 있습니다 angularjs v1.4.9)

(function(angular) {
    "use strict";

    function $stateDecorator($delegate, $injector, $rootScope, appSettings) {
        function decorated$State() {
            var $state = $delegate;
            $state.previous = undefined;
            $rootScope.$on("$stateChangeSuccess", function (ev, to, toParams, from, fromParams) {
                $state.previous = { route: from, routeParams: fromParams }
            });

            $rootScope.$on("$stateChangeStart", function (event, toState/*, toParams, fromState, fromParams*/) {
                var authenticationFactory = $injector.get("authenticationFactory");
                if ((toState.name === appSettings.states.login || toState.name === appSettings.states.register) && authenticationFactory.isUserLoggedIn()) {
                    event.preventDefault();
                    $state.go(appSettings.states.index);
                }
            });

            return $state;
        }

        return decorated$State();
    }

    $stateDecorator.$inject = ["$delegate", "$injector", "$rootScope", "appSettings"];

    angular
        .module("app.core")
        .decorator("$state", $stateDecorator);
})(angular);

$ stateChangeStart의 $ state에 {previous}라는 새 속성을 추가하십시오.

$rootScope.$on( '$stateChangeStart', ( event, to, toParams, from, fromParams ) => {
    // Add {fromParams} to {from}
    from.params = fromParams;

    // Assign {from} to {previous} in $state
    $state.previous = from;
    ...
}

이제 필요한 곳이라면 어디든지 $ state를 사용할 수 있습니다.

previous:Object
    name:"route name"
    params:Object
        someParam:"someValue"
    resolve:Object
    template:"route template"
    url:"/route path/:someParam"

그리고 그렇게 사용하십시오 :

$state.go( $state.previous.name, $state.previous.params );

나는 같은 문제에 봉착하고 이것을 수행하는 가장 쉬운 방법을 찾습니다 ...

//Html
<button type="button" onclick="history.back()">Back</button>

또는

//Html
<button type="button" ng-click="goBack()">Back</button>

//JS
$scope.goBack = function() {
  window.history.back();
};

더 테스트 가능하게하려면 $ window 서비스를 컨트롤러에 주입하고 $ window.history.back ()을 사용하십시오.


Endy Tjahjono가하는 것과 비슷한 접근법을 사용합니다.

내가하는 것은 전환하기 전에 현재 상태의 값을 저장하는 것입니다. 예를 보자. 전환을 트리거하는 모든 항목을 클리 킹 할 때 실행되는 함수 내에서 이것을 상상해보십시오.

$state.go( 'state-whatever', { previousState : { name : $state.current.name } }, {} );

여기서 핵심은 params 객체 (상태로 보내질 매개 변수의 맵)입니다-> { previousState : { name : $state.current.name } }

참고 : Im은 상태를 저장하는 데 필요한 유일한 것이므로 $ state 객체의 이름 속성 만 "저장"한다는 점에 유의하십시오. 그러나 우리는 전체 상태 객체를 가질 수 있습니다.

그런 다음 "whatever"라고 다음과 같이 정의하십시오.

.state( 'user-edit', {
  url : 'whatever'
  templateUrl : 'whatever',
  controller: 'whateverController as whateverController',
  params : {
    previousState: null,
  }
});

여기서 핵심은 params 객체입니다.

params : {
  previousState: null,
}

그런 다음 그 상태 안에서 다음과 같이 이전 상태를 얻을 수 있습니다.

$state.params.previousState.name

다음은 Chris Thielen ui-router-extras 의 정말 우아한 솔루션입니다 . $ previousState

var previous = $previousState.get(); //Gets a reference to the previous state.

previous is an object that looks like: { state: fromState, params: fromParams } where fromState is the previous state and fromParams is the previous state parameters.


Ok, I know that I am late to the party here, but I am new to angular. I am trying to make this fit into the John Papa style guide here. I wanted to make this reusable so I created in a block. Here is what I came up with:

previousStateProvider

(function () {
'use strict';

angular.module('blocks.previousState')
       .provider('previousState', previousStateProvider);

previousStateProvider.$inject = ['$rootScopeProvider'];

function previousStateProvider($rootScopeProvider) {
    this.$get = PreviousState;

    PreviousState.$inject = ['$rootScope'];

    /* @ngInject */
    function PreviousState($rootScope) {
        $rootScope.previousParms;
        $rootScope.previousState;
        $rootScope.currentState;

        $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
            $rootScope.previousParms = fromParams;
            $rootScope.previousState = from.name;
            $rootScope.currentState = to.name;
        });
    }
}
})();

core.module

(function () {
'use strict';

angular.module('myApp.Core', [
    // Angular modules 
    'ngMessages',
    'ngResource',

    // Custom modules 
    'blocks.previousState',
    'blocks.router'

    // 3rd Party Modules
]);
})();

core.config

(function () {
'use strict';

var core = angular.module('myApp.Core');

core.run(appRun);

function appRun(previousState) {
    // do nothing. just instantiating the state handler
}
})();

Any critique on this code will only help me, so please let me know where I can improve this code.


If you just need this functionality and want to use it in more than one controller, this is a simple service to track route history:

  (function () {
  'use strict';

  angular
    .module('core')
    .factory('RouterTracker', RouterTracker);

  function RouterTracker($rootScope) {

    var routeHistory = [];
    var service = {
      getRouteHistory: getRouteHistory
    };

    $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
      routeHistory.push({route: from, routeParams: fromParams});
    });

    function getRouteHistory() {
      return routeHistory;
    }

    return service;
  }
})();

where the 'core' in .module('core') would be the name of your app/module. Require the service as a dependency to your controller, then in your controller you can do: $scope.routeHistory = RouterTracker.getRouteHistory()


I keep track of previous states in $rootScope, so whenever in need I will just call the below line of code.

$state.go($rootScope.previousState);

In App.js:

$rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams) {
  $rootScope.previousState = from.name;
});

For UI-Router(>=1.0), StateChange events have been deprecated. For complete migration guide, click here

To get the previous state of the current state in UI-Router 1.0+:

app.run(function ($transitions) {
    $transitions.onSuccess({}, function (trans) {
         // previous state and paramaters
         var previousState = trans.from().name;
         var previousStateParameters = trans.params('from');
    });
});

A really simple solution is just to edit the $state.current.name string and cut out everything including and after the last '.' - you get the name of the parent state. This doesn't work if you jump a lot between states because it just parses back the current path. But if your states correspond to where you actually are, then this works.

var previousState = $state.current.name.substring(0, $state.current.name.lastIndexOf('.'))
$state.go(previousState)

You can return the state this way:

$state.go($state.$current.parent.self.name, $state.params);

An example:

(function() {
    'use strict'

    angular.module('app')
        .run(Run);

    /* @ngInject */
    function Run($rootScope, $state) {

        $rootScope.back = function() {
            $state.go($state.$current.parent.self.name, $state.params);
        };

    };

})();

참고URL : https://stackoverflow.com/questions/16635381/angular-ui-router-get-previous-state

반응형