Simple Angular $routeProvider resolve test. What is wrong with this code?

╄→гoц情女王★ 提交于 2019-11-29 07:37:25

The problem is that you have ng-controller="ResolveCtrl" on your body tag in index.html when also in your $routeProvider you specify the same controller for rt.html. Take out the controller definition from your body tag and just let the $routeProvider take care of it. It works great after that.

According to the angularjs documentation for $routeprovider the resolve object is a map from key (dependency name) to factory function or name of an existing service. Try this instead:

var myFactory = function($q, $timeout) { ... };
myFactory.$inject = ['$q', '$timeout'];

$routeProvider.when("/",{
    templateUrl: "rt.html",
    controller: "ResolveCtrl",
    resolve: {
      data: myFactory
    }
});

By adding data to the definition of the controller your telling angular that you expect to inject a service or factory here yet you don't have a data service or factory thus the error. To use the data variable you have all you need from the $scope.data line. So to fix this you need to remove the data injection from your controller call.

var rt = angular.module("ResolveTest",[]);

rt.config(["$routeProvider",function($routeProvider)
{
  $routeProvider.when("/",{
    templateUrl: "rt.html",
    controller: "ResolveCtrl",
    resolve: {
      data: ["$q","$timeout",function($q,$timeout)
      {
        var deferred = $q.defer();

        $timeout(function()
        {
          deferred.resolve("my data value");
        },2000);

        return deferred.promise;
      }]
    }
  });
}]);

rt.controller("ResolveCtrl",["$scope", function($scope)
{
  $scope.data = "";
}]);

If you want to have a data provider add a factory something like

rt.factory('data', ['$http', function($http){
 return {
   // Functions to get data here
 }
}]);

Then in your controller call the appropriate function from this factory.

Also as the others have pointed out you don't need the controller both in your route and in an ng-controller (this will nest your controller in your controller if you inspect the scopes).

If you must use resolve you still need a factory as resolve will just point to the proper factory which needs to be declared separately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!