Updating resolved objects in ui.router parent states

前端 未结 2 1076
有刺的猬
有刺的猬 2020-12-07 01:59

My question is two fold:

1 - I have a parent state and several child states using ui.router, there\'s one object (stored in mongodb) that is need in all states, but

2条回答
  •  粉色の甜心
    2020-12-07 02:22

    you could store it in a service.

    .service("myService", function($q) { 
      // the actual data is stored in a closure variable
      var data = undefined;
      return { 
        getPromise: function() { // promise for some data
          if (data === undefined) // nothing set yet, go fetch it
            return $http.get('resourceurl').then(function(value) { data = value; return data; });
          else
            return $q.when(data); // already set, just wrap in a promise.
        },
        getData: function() { return data; }, // get current data (not wrapped)
        setData: function(newDataVal) { data = newDataVal; } // reset current data
      }
    })
    
    // `parent` wont' enter until getPromise() is resolved. 
    .state('parent', resolve:{objectX: function(myService) { return myService.getPromise(); } });
    
    .controller('childstateCtrl', $scope, myService) {
        $scope.data.objectX = myService.getData();
        $scope.someEvent = function(someData){ 
          myService.setData(someData);
        }
    }
    
    .controller('otherChildCtrl', $scope, myService){
        // how to get the updated objectX?
        var data = myService.getData();
    }
    

提交回复
热议问题