search

Home  >  Q&A  >  body text

angular.js - Injection of resolve in controller fails in angularjs routing

Because it is found that resolve is not only triggered when loaded, but also triggered when returning, but the controller obtained is not updated when returning.
In this example, the things obtained by resolve are also put in the service to get them. I originally wanted to try changing to the injection method to see if the situation is the same. If it still doesn't work, I plan to put it in the service or resolve. The data is only used when loaded.
So I wanted to find an example to test it, but the injection always failed.

There is no test injected here. An error will be reported when injected.
http://jsfiddle.net/abelmakihara/x99b2o2p/3/http://jsfiddle.net/abelmakihara/x99b2o2p/3/

高洛峰高洛峰2757 days ago776

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-15 17:04:13

    That’s it. I looked at it carefully. There is something wrong with your understanding of ngRoute. I changed it. Please take a look again: jsFiddle

    The main difference is:

    app.factory('rulesFactory', ['$q', '$timeout',
      function($q, $timeout) {
        return function() {
          return $q(function(resolve){
              $timeout(function() {
                  //这里如果期待返回值,就要用$q封装,并resolve
                  resolve('Change time in seconds:' + new Date().getTime() / 1000);
              }, 1000)
          });
        };
      }
    ]);
    $routeProvider
    .when('/', {
        action: 'index',
        resolve: {
            //这里的resolve真对的是该路由自己的controller
            'test': ['rulesFactory', function(rulesFactory) {
                return rulesFactory();
            }]
        },
        //所以一定要定义一个自己的AController
        controller: 'AController',
        template: '<h3>{{test}}</h3>'
    })
    .when('/page', {
        action: 'page',
        resolve: {
            'test': ['rulesFactory', function(rulesFactory) {
                return rulesFactory();
            }]
        },
        controller: 'BController',
        template: '<h3>{{test}}</h3>'
    })
    //然后,AController,BController就可以注入test了,并且test的值就是上面resolve的那堆字符串
    app.controller('AController', ['$scope', 'test',
    
      function($scope, test) {
        $scope.test = test;
      }
    ]);
    
    app.controller('BController', ['$scope', 'test',
    
      function($scope, test) {
        $scope.test = test;
      }
    ]);

    reply
    0
  • Cancelreply