注入应该注入控制器的resolve
的返回对象,但事实并非如此。我正在使用一个承诺,以便在承诺解决之前控制器不会实例化,因为我正在使用$http
服务进行HTTP POST。
我也使用$location.path
根据响应数据进行一些重定向。第一条路线将使用已获取的数据重定向到template1
路线。
$routeProvider
.when("/auth/:id", amd.route(
{
controller: 'eventController',
controllerUrl: 'app/controllers/eventController',
resolve: {
returnedData: ['$http', '$location', '$route', '$q', function ($http, $location, $route, $q) {
var id = $route.current.params.id;
var defer = $q.defer();
$http({
method: 'POST',
url: 'http://domain/service/webapi',
data: { 'name': id }
}).then(function (response) {
var template = "/template".concat(response.data.displayLayout);
defer.resolve(response.data);
$location.path(template);
return defer.promise;
});
}]
}
}))
.when("/template1", amd.route(
{
templateUrl: 'views/templates/template1.html',
controller: 'eventController',
controllerUrl: 'app/controllers/eventController',
}));
app.controller('eventController', ['$scope', '$routeParams', '$timeout', 'returnedData',
function ($scope, $routeParams, $timeout, returnedData) {
// ...controller code here: $scope.returnedData = returnedData
});
我收到了AngularJS错误:
错误:$ injector:unpr未知提供商
对此有何想法?
答案 0 :(得分:1)
在AngularJS API页面中,关于routeProvider(https://docs.angularjs.org/api/ngRoute/provider/ $ routeProvider)
你可以看到:resolve - {Object。=} ...如果这些依赖项中的任何一个是promise,路由器将等待它们全部被解析或者在实例化控制器之前被拒绝一个
您应该如下编辑代码:
var id = $route.current.params.id;
var defer = $q.defer();
$http({
method: 'POST',
url: 'http://domain/service/webapi',
data: { 'name': id }
}).then(function (response) {
var template = "/template".concat(response.data.displayLayout);
defer.resolve(response.data);
$location.path(template);
});
// return the promise outside `then` method, then angularjs will wait it `resolve`
return defer.promise;
更进一步,请注意:
请注意,ngRoute。$ routeParams仍然会引用这些解析函数中的上一个路由。而是使用$ route.current.params来访问新的路由参数。
答案 1 :(得分:-1)
在ng-route中使用依赖注入, 我的解决方案:
var myApp = angular.module("myApp", ["ngRoute", "localytics.directives"]);
myApp.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "//TimeLine.html",
controller: "MainCtrl"
})
.when("/AddOrEditOccasion", {
templateUrl: "/Html/GiftWhiz/AddOrEditOccasion.html",
controller: "AddOrEditOccasionCtrl"
})
.when("/OccasionStart", {
templateUrl: "/OccasionStart.html",
controller: "OccasionStartCtrl"
})
}]);
myApp.controller("MainCtrl", ['$scope', '$http', '$location', function ($scope, $http, $location) {
//your codes
}]);