Inject controller in $routeProvider resolve method - javascript

Following the main answer here, I've tried to do the same, with the exception that my controller is isolated.
I get this:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
ReferenceError: myController is not defined
I only get this when the resolve: parameter is present.
How can I work around this one ?
Route config:
.state("my.jobs", {
url: "/my/:jobId",
templateUrl: "Views/my/index.htm",
controller: "myController",
resolve: myController.resolve // the root of all evil here
})
controller:
(function (ng, app) {
"use strict";
var ctrl = app.controller(
"myController",
['$scope', 'job',
function ($scope, job) {
$scope.job = job;
}]);
ctrl.resolve = {
job: function ($q, $stateParams, batchService) {
var deferred = $q.defer();
jobService.loadJob($stateParams.jobId, true)
.then(deferred.resolve, deferred.reject);
},
delay: function ($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
};
})(angular, myApp);
I don't want to make the controller a global function, I like it isolated as it is.

In your case you could create one service, that you can consume inside your resolve function.
app.factory('resolveService', ['$q', '$stateParams', 'batchService','jobService',function($q, $stateParams, batchService,jobService ) {
return {
job: function($q, $stateParams, batchService) {
var deferred = $q.defer();
jobService.loadJob($stateParams.jobId, true).then(deferred.resolve, deferred.reject);
return delay.promise;
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
}]);
Then the config code will be
.state("my.jobs", {
url: "/my/:jobId",
templateUrl: "Views/my/index.htm",
controller: "myController",
resolve: {
resolveService: "resolveService" //this resolves to a service
}
});
For more info look at this reference

Related

RouteProvider resolve AngularJS

Here is my code :
Js:
angular.module('main', [])
.config(['$locationProvider', '$routeProvider',
function($locationProvider, $routeProvider) {
$routeProvider.when('/tables/bricks', {
controller: "myController",
resolve: {
"check" : function($location){
if(!$scope.bricks) {
$route.reload();
}
}
},
templateUrl: 'tables/bricks.html'
});
$routeProvider.otherwise({
redirectTo: '/tables/datatables'
});
}
])
.controller('myController', function($scope, $location, $http) {
var vm = this;
$scope.Bricks = function(){
$location.path('/tables/bricks');
};
vm.getbricks = function(n){
var url = n;
$http({
method: 'GET' ,
url: url,
})
.then(function successCallback(data) {
$scope.bricks = data.data;
console.log($scope.bricks);
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
});
HTML:
<button ng-click="vm.getbricks(n.bricks_url);Bricks();"></button>
After click the button in html, my page goes into /tables/bricks, but nothing happend, because resolve probably is wrong. What I want - that i could go to /tables/bricks only then, when $scope.bricks exist, so only when vm.bricks() will be called.
Thanks for answers in advance!
I think your problem is that the vm.getbricks will always return something (in success or error handler), so will never be falsy, and you will always call the Bricks() constructor. try to return true on success callback and false in error callback.
$scope is for controllers, which it can't reach in the config. Instead, you should be returning something from a service, which will be called during your resolve. E.g. if(YourService.getbricks())
Solution: move your logic from a controller into a service. And make sure to return a value from it that can be checked in the config.
app.service('BrickService', function() {
this.getbricks = function(url) {
return $http.get(url) // return the Promise
.then(function(response) {
return response.data; // return the data
}, function(error) {
console.log(error);
});
};
});
With this you can inject the service into the config and run its function.
angular.module('main', [])
.config(['$locationProvider', '$routeProvider',
function($locationProvider, $routeProvider) {
$routeProvider.when('/tables/bricks', {
controller: "myController",
resolve: {
"check": function(BrickService) { // inject
if ( BrickService.getbricks() ) { // run its function
$route.reload();
}
}
},
templateUrl: 'tables/bricks.html'
});
$routeProvider.otherwise({
redirectTo: '/tables/datatables'
});
}
])
You can also use the loaded values in the controller after they have been resolved. For that, you would need to simply return it. So change the logic to this:
resolve: {
"check": function(BrickService) { // inject
var bricks = BrickService.getbricks(); // run its function
if ( bricks ) {
$route.reload();
}
return bricks; // return the result (note: it's not a Promise anymore)
}
}
Then you can inject this resolve into your controller:
.controller('myController', function($scope, $location, $http, check) {
var vm = this;
vm.bricks = check;
...
(Note check was added)

unable to inject a service in controller

I am using requireJS for my angularjs app.
common.service.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.config(['$provide', function ($provide) {
$provide.factory("CommonService", CommonService);
}]);
CommonService.$inject = ["$http", "$q", "$window"];
function CommonService($http, $q, $window) {
var service = {};
service.sharedValue;
return service;
}
});
page1.controller.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
// Q2: common service
$scope.commonService = CommonService;
}]);
});
Now When I am running my app, it throws me below error:
Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService <- Page1Controller
any inputs?
Your core module should have empty dependencies injected
var coreModule = angular.module('coreModule',[]);
Also in page1. controller you dont have to declare the module again, you can just use
angular.module('coreModule')
.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
Define config
Define the service
Define the controller, inject the service, use the dependency in function declaration etc. As you would know, both are needed, after all you need the those handles, else what's the point in injecting.
Define a module, define module dependencies. NOTE that the service has to be defined before controller. If you reverse the order, you will get an error, probably that's what is happening here. Without full code, I can't tell.
bootstrap angular.
Finally working plunkr: http://plnkr.co/edit/CE9enkgW3KASx8pf5vdb?p=preview
define('config',[],function(){
function config($routeProvider) {
$routeProvider.when('/home', {templateUrl: 'tpl.home.html', controller: 'HomeController'})
.otherwise({redirectTo: '/home'});
}
config.$inject=['$routeProvider'];
return config;
});
define('dataSvc',[], function(app){
function factoryFunc ($q, $timeout){
var svc = {getData: getData};
return svc;
function getData() {
console.log('executing function');
var d = $q.defer();
$timeout(function(){
console.log("firing timeout");
d.resolve({name:"test", data:[1, 2, 3, 4]});
}, 750);
return d.promise;
}
}
factoryFunc.$inject=['$q', '$timeout'];
return factoryFunc;
});
define('HomeController',[], function() {
function HomeController($scope, dataSvc) {
$scope.name = "Mahesh";
dataSvc.getData().then(function(result){
$scope.data=result;
console.log($scope.data);
});
}
HomeController.$inject=['$scope','dataSvc'];
return HomeController;
});
define('coreModule', ['config', 'dataSvc', 'HomeController']
, function(config, dataSvc, HomeController){
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(config);
app.factory('dataSvc',dataSvc);
app.controller('HomeController', HomeController);
});
require(['coreModule'],
function() {
angular.bootstrap(document, ['app']);
}
);
Refer also,
https://www.sitepoint.com/using-requirejs-angularjs-applications/
http://beletsky.net/2013/11/using-angular-dot-js-with-require-dot-js.html

angular unknown provider error using factory and ui.router resolve

I'm getting unknown provider error when i'm trying to use resolve from a state. The object i want returned seems to be returned correctly, so i can't really figure out what the problem is.
This is my first angular project so if I something seems wierd it probably is.
The error: https://docs.angularjs.org/error/$injector/unpr?p0=boardProvider%20%3C-%20board%20%3C-%20AppCtrl
var ponk = angular.module("ponk", ["ui.router", "ngResource"]);
ponk.config(['$stateProvider', '$urlRouterProvider',
"$locationProvider", function ($stateProvider, $urlRouterProvider,
$locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider.state('board', {
url: '/b/:slug',
templateUrl: 'views/board.html',
controller: "AppCtrl",
controllerAs: "pk",
resolve: {
board: function($stateParams, boardFactory) {
var board = {};
if($stateParams.slug) {
board = boardFactory.get({slug:$stateParams.slug}).$promise;
}
return board;
}
}
});
}]).run(function($state) { $state.go('board'); });;
ponk.factory("boardFactory", ["$http", "$resource",
function($http, $resource) {
return $resource('/board/:slug', {slug:'slug'}, {update: { method: "PUT" }});
}]);
ponk.controller("AppCtrl", ["$scope", "$http", "boardFactory", "board",
function($scope, $http, boardFactory, board ) {
console.log(board); // correct object, but error
}]);
EDIT:
discovered the above code works. The problem is when i add this to the controller:
var pk = this;
var pk.board = board;

Cannot read property of undefined angular factory

I have issue with Angular factory, I've tried many ways, but it's same..
This is error:
TypeError: Cannot read property 'getSchedule' of undefined
at new <anonymous> (http://127.0.0.1:4767/js/ctrls/main.js:3:19)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:35:36)
at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:35:165)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:67:419
at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js:7:248)
at N (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:54:372)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:256)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:46:377
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:48:217
at F (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:52:28) <ng-view class="app-content ng-scope" ng-hide="loading">
I have constructed main app this way:
'use strict';
// Declare chat level module which depends on views, and components
angular.module('BenShowsApp', [
'ngRoute',
'ngResource',
'mobile-angular-ui',
'BenShowsApp.filters',
'BenShowsApp.services',
'BenShowsApp.directives',
'BenShowsApp.controllers'
]).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/schedule', {
templateUrl: 'partials/main.html',
controller: 'MainCtrl'
});
}]);
//Initialize individual modules
var services = angular.module('BenShowsApp.services', []);
var factories = angular.module('BenShowsApp.factories', []);
var controllers = angular.module('BenShowsApp.controllers', []);
var filters = angular.module('BenShowsApp.filters', []);
var directives = angular.module('BenShowsApp.directives', []);
and tried use this factory/service
services.factory('tvRage', function($http) {
var tvRage = {};
tvRage.getSchedule = function() {
return $http({
method: 'get',
url: 'http://services.tvrage.com/feeds/fullschedule.php',
params: {
country: 'US',
key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
}).then(function (response) {
return response.data;
});
};
return tvRage;
});
with this controller
controllers.controller('MainCtrl', ['$scope','$http','tvRage',
function ($scope, $http, tvRage) {
tvRage.getSchedule().success(function(data){
var parser = new X2JS();
var x2js = parser.xml_str2json(data);
$scope.request = x2js;
}).error(function(){
alert('nouuu');
});
}
]);
$http works when it's all in controller, but from functional side that request should be in factory I think.
You are returning $q promise from the factory. It does not have the methods success and error they are special functions added by $http in the returned httpPromise (which is just an extension of QPromise).
You can either change your factory to return httpPromise by removing the then chaining:
return $http({
method: 'get',
url: 'http://services.tvrage.com/feeds/fullschedule.php',
params: {
country: 'US',
key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
});
Or chain it in your controller with standard q promise functions then/ catch.
controllers.controller('MainCtrl', ['$scope','$http','tvRage',
function ($scope, $http, tvRage) {
tvRage.getSchedule().then(function(data){
var parser = new X2JS();
var x2js = parser.xml_str2json(data);
$scope.request = x2js;
}).catch(function(){
alert('nouuu');
});
}
]);
But with the specific error you are getting it looks like possibly in your original code your DI list does not match argument list. Re-verify by logging what is tvRage and other arguments injected in the controller. This could easily happen because of argument mismatch in the original code. Ex:-
.controller('MainCtrl', ['$scope','tvRage', function ($scope, $http, tvRage){
//Now tvRage will be undefined and $http will be tvRage.
Working Demo
angular.module('app', []).controller('ctrl', ['$scope', '$http', 'tvRage',
function($scope, $http, tvRage) {
tvRage.getSchedule().success(function(data) {
console.log(data)
}).error(function() {
alert('nouuu');
});
}
]).factory('tvRage', function($http) {
var tvRage = {};
tvRage.getSchedule = function() {
return $http({
method: 'get',
url: 'http://services.tvrage.com/feeds/fullschedule.php',
params: {
country: 'US',
key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
});
};
return tvRage;
});;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>

Angular route resolve not waiting for promise

I'm new to angular and I have a user route which I'm attempted to resolve the user object for before rendering the view. I've injected $q and deferred the promise, however, the view is still loading before the promise is returned.
Route:
.when('/user/:userId', {
templateUrl: 'user/show.html',
controller: 'UserController',
resolve: {
user: userCtrl.loadUser
}
})
Controller
var userCtrl = app.controller('UserController', ['$scope',
function($scope){
$scope.user = user; // User is undefined
// This fires before the user is resolved
console.log("Fire from the controller");
}]);
userCtrl.loadUser = ['Restangular', '$route', '$q',
function(Restangular, $route, $q) {
var defer = $q.defer();
Restangular.one('users', $route.current.params.userId).get().then(function(data) {
console.log("Fire from the promise");
defer.resolve(data);
});
return defer.promise;
}];
After looking through the Github issues, I found a similar problem and resolved it with the following:
userCtrl.loadUser = ['Restangular', '$route',
function(Restangular, $route) {
return Restangular.one('users', $route.current.params.userId).get();
}];

Categories

Resources