How to inherit resolve data in ui-router

前端 未结 1 596
长发绾君心
长发绾君心 2020-12-08 22:54

I have a tricky situation here. my parent state and child state are both overriding the same ui view at the top level(index.html). So when it goes to the child state from th

相关标签:
1条回答
  • 2020-12-08 23:31

    I. The answer to question:

    ... child since its not nested ... Is there a way to get that metricdata property in the child?

    Is based on

    What Do Child States Inherit From Parent States?

    Child states DO inherit the following from parent states:

    • Resolved dependencies via resolve
    • Custom data properties

    Nothing else is inherited (no controllers, templates, url, etc).

    in conjuction with

    Scope Inheritance by View Hierarchy Only

    Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).

    It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.

    II. While this should be clear now, we still need to find a way how to solve:

    ... Is there a way to get that metricdata property in the child without having to manually call the same ajax call again in the child..

    And I would say, there is also answer. E.g.

    • Angular UI Router Nested State resolve in child states
    • How do I prevent reload on named view, when state changes? AngularJS UI-Router

    .. move the shared views/resolvers to the least common denominator. ..

    E.g. we can do it like in this Q & A: Controlling order of operations with services and controllers, see the plunker:

    A special grand parent / root state:

    $stateProvider
      .state('root', {
        abstract : true,
        // see controller def below
        controller : 'RootCtrl',
        // this is template, discussed below - very important
        template: '<div ui-view></div>',
        // resolve used only once, but for available for all child states
        resolve: {
          user: function (authService) {
              return authService.getUserDetails();
          }
        }
      }) 
    

    Passing resolved stuff into $scope (inherited by each child)

    .controller('RootCtrl', function($scope,user){
      $scope.user = user;
    })
    

    This is injected on top of our state / view hierarchy, and any child state would profit from it

    // any previously root state will just use the above as a parent
    .state('index', {
        url: '/',
        parent : 'root',
    

    Check more details here and see it in a working example

    0 讨论(0)
提交回复
热议问题