angular.js - Injection of resolve in controller fails in angularjs routing
高洛峰
高洛峰 2017-05-15 17:02:13
0
1
769

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/

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
小葫芦

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;
  }
]);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template