when using ui-router resolve, how do I access the resolved data?

前端 未结 3 898
一个人的身影
一个人的身影 2021-01-06 06:42

I have the following routes:

$stateProvider
    .state(\"base\",
    {
        url: \"\",
        abstract: true,
        resolve: {
            aService:          


        
3条回答
  •  广开言路
    2021-01-06 07:24

    Based on this Q & A

    angular-ui-router with requirejs, lazy loading of controller

    I created this working plunker, which is able to load controller with RequireJS and inject state resolve - from Parent or from the Child itself

    This would be the state defintion:

    $stateProvider
      .state("base",
      {
        abstract: true,
        resolve: {
            dataNeeded: function(aService) {
              return aService.getDataMethod()
                .then(function(response){ return response.data }); //.$promise;
            }
        },
        template: "",
    
      });
    
    $stateProvider
      .state("base.other", {
        url: "/other",
        template: "
    The message from ctrl: {{message}}" + "
    and someResolved: {{someResolved}}" + "
    and dataNeeded:
    {{dataNeeded | json}}
    " + "
    ", controller: "OtherCtrl", resolve: { someResolved: function() { return "This is resolved value for key 'someResolved'" }, loadOtherCtrl: ["$q", function($q) { var deferred = $q.defer(); require(["OtherCtrl"], function() { deferred.resolve(); }); return deferred.promise; }], }, });

    For more details read complete explanation here...

    And this is the controller for RequireJS:

    define(['app'], function (app) {
        // the Default Controller
        // is added into the 'app' module
        // lazily, and only once
        app_cached_providers
          .$controllerProvider
          .register('OtherCtrl',['$scope', 'dataNeeded', 'aService', 'someResolved', 
            function ($scope, dataNeeded, aService, someResolved) {
              $scope.message = "OtherCtrl";
              $scope.someResolved = someResolved;
              $scope.dataNeeded = dataNeeded;
              console.log(dataNeeded)
              console.log(aService)
              console.log(someResolved)
        }]);
    
    });
    

    Check it here in action

提交回复
热议问题