我如何纠正注入依赖P48Wallet以解决$ routeProvider?
app.js
'use strict';
define(
[
'angularAMD',
'angular-route',
'angular-animate'
],
function (angularAMD) {
var app = angular.module('FilmOrder', ['ngRoute', 'ngAnimate']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/',
angularAMD.route({
templateUrl: 'static/js/application/views/main.html',
controller: 'application/controllers/Main',
resolve: {
films:
require(['application/services/P48Wallet', function(P48Wallet) {
return P48Wallet.getUserData();
}])
}
})
)
.when('/success',
angularAMD.route({
templateUrl: 'static/js/application/views/success.html',
controller: 'application/controllers/Success'
})
)
.otherwise({redirectTo: '/'});
}]);
angularAMD.bootstrap(app);
return app;
});
=============================================== ==========
P48Wallet.js
'use strict';
define(['application/app', 'application/services/Http'], function(app) {
return app.factory('P48Wallet', function(Http) {
this.getUserData = function() {
return Http.post('?action=get_data');
};
return this;
});
});
=============================================== ==========
我收到错误:
Error: [$injector:unpr] http://errors.angularjs.org/undefined/$injector/unpr?p0=dProvider%20%3C-%20d
答案 0 :(得分:1)
我可以看到2个问题:
angularAMD.route
设置resolve
属性,以便覆盖
您正在设置的resolve
。return app.factory
期望一个对象返回而不是this
您应该做的是将P48Wallet
定义为工厂/服务,然后将其添加到您的Main
控制器的依赖项中。例如:
<强>应用/服务/ P48Wallet.js 强>
编辑:添加功能以从每个评论的POST缓存返回的数据。
define(['application/app', 'application/services/Http'], function(app) {
app.register.service('P48Wallet', function(Http, $q) {
var priv_data;
// Assuming that your Http works the same way as $http
this.getUserData = function() {
var d = $q.defer();
if (priv_data) {
// Return cached value
d.resolve(priv_data);
} else {
Http.post('?action=get_data')
.then(function (data) {
priv_data = data;
d.resolve(data);
})
.catch(function (error) {
d.reject(error);
});
}
};
return d.promise;
});
});
<强>应用/控制器/ Main.js 强>
define(['application/app', 'application/services/P48Wallet'], function (app) {
app.register.controller("MainController", [
'$scope', 'P48Wallet', function ($scope, P48Wallet) { ... }
]);
});
<强>应用/ app.js 强>
// Keeping everything the same except
angularAMD.route({
templateUrl: 'static/js/application/views/main.html',
controllerUrl: 'application/controllers/Main',
controller: 'MainController'
})
这是angularAMD关于如何设置到延迟加载控制器的路由的文档:
https://github.com/marcoslin/angularAMD#on-demand-loading-of-controllers