AngularJS routeProvider with lazy loading to use values from WebAPI - angularjs

I have a routeProvider that lazy loads various modules. I based my implementation on these two articles:
https://codereview.stackexchange.com/questions/42581/dynamic-routing-with-lazy-load-controllers
http://ify.io/lazy-loading-in-angularjs/
It looks like this and works just fine:
myApp.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/startpage.html',
controller: 'startPageController',
}).
otherwise({
resolve: {
deps: function ($q, $rootScope, $location) {
var deferred = $q.defer();
var path = $location.path();
var modulename = $location.path().split("/")[1];
if (modulename != null) {
var scriptfile = '/Scripts/' + modulename + 'controller.js';
$script(scriptfile, function () {
$rootScope.$apply(function () {
//reprocess the route
$rootScope.$broadcast('$locationChangeSuccess', path, path);
});
});
}
return deferred.promise;
}
}
});
});
Now I would like to check the modulename variable against values returned from a WebAPI. If the value of modulename is not in the returned array, I want the AngularJS to be redirected to the root (/).
I tried injecting $http in the deps function, but using it there causes it to be loaded several times. This is also not very efficient as the data should be retrieved once and then the result used. I cannot, however, find a way to retrieve the data from the WebAPI outside of the deps function (because $http can't be injected into the myApp.config).
How could I go about changing the myApp.config to get a list of approved "modules" from the WebAPI, then using this list to generate the routes?

I ended up using something entirely different.
Because each route is defined in each module's controller, I use the WebAPI to get all the available module, then I lazy load that module's controller, which sets up the correct routes. I do this in the AngularJS app's run method, as that has access to the $http variable.
This is the result:
myApp.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/startpage.html',
controller: 'startPageController',
}).
otherwise({
redirectTo: '/'
});
});
myApp.run(function($http) {
$http.get('/webapi/modules').success(function(data) {
angular.forEach(data, function (module, key) {
var scriptfile = '/Scripts/' + module + 'controller.js';
$script(scriptfile, function () {});
});
});
});
Probably not the most elegant or sofisticated solution, but it works.

Related

Controller Undefined after Form Submit: Argument 'RegistrationController' is not a function, got undefined

I wrote some custom routing in my app configuration file to handle routing of all my html templates and controllers instead of having to specifically define the route for every single html and controller. I have a Registration.html and RegistrationController.js under my Modules/Account/ directory. My app can find the controller the first time I go to it and I can fill out the page and submit the form on the page. After I submit successfully, I get redirected to a success page. When I try to go back to the same registration html/controller the 2nd time, it can find my html template, but it can not find my controller anymore and i get the error "Argument 'RegistrationController' is not a function, got undefined". Can anyone tell me why and how to fix this?
Please note this error only happens after a form submit. If I leave the page and go back to it without doing a form submit, everything works fine.
App Config
define(['angularAMD', 'angular-route', 'ui-bootstrap', 'ui-grid'], function (angularAMD) {
var app = angular.module("MyApp", ['ngRoute', 'ui.bootstrap', 'ui.grid']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", angularAMD.route({
templateUrl: function (rp) { return 'Modules/Account/login.html'; },
controllerUrl: 'Modules/Account/LoginController'
}))
.when("/:module/:page", angularAMD.route({
templateUrl: function (rp) { return 'Modules/' + rp.module + '/' + rp.page + '.html'; },
resolve: {
load: ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {
var path = $location.path();
var parsePath = path.split('/');
var parentPath = parsePath[1];
var controllerName = parsePath[2];
var loadController = "Modules/" + parentPath + "/" + controllerName + "Controller";
debugger;
var deferred = $q.defer();
require([loadController], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
}))
.otherwise({ redirectTo: '/' });
}]);
loadDirectives(app);
angularAMD.bootstrap(app);
return app;
});
RegistrationController
define(['app-config','accountService'], function (app) {
app.register.controller('RegistrationController', ['$scope', '$rootScope', '$location', '$uibModal', 'accountService',
function ($scope, $rootScope, $location, $uibModal, accountService) {
$rootScope.applicationModule = "Account";
$scope.registerUserSuccess = function (response, status) {
debugger;
$location.path("/Account/RegistrationSuccess");
}
$scope.registerUserFailure = function (response, status) {
if (!response.ValidationErrors) {
$scope.ErrorList = [];
$scope.ErrorList.push("An error occurred. Please contact the system's administrator");
}
else {
$scope.ErrorList = response.ValidationErrors;
}
}
$scope.onSubmitClick = function (isValid) {
if (isValid) {
accountService.registerUser($scope.regModel, $scope.registerUserSuccess, $scope.registerUserFailure);
}
}
$scope.onCancelClick = function () {
$location.path("/Login");
}
}
]);
});
I haven't honed in on the answer yet, but I've noticed some refactoring that you should do that might get you closer to figuring out your problem ...
Stop using controllers. Use components, which were introduced in 1.5. These are superior in their reusability. They are more flexible in how you can use them and in what you can pass into them. The only controllers you should be using are the ones in components.
Stop using $scope or $rootScope for anything. Used named controllers. This is the default setting for a component.
Consider ui-router over angular-route. It's just a lot better.
What is loadDirectives(app) doing?
Put a log statement in your RegistrationContoller.js and just verify that it isn't being called more than once. If it thinks RegistrationController is undefined after previously being defined, it just feels like it's being defined more than once.
Is there anything fishy in accountService.registerUser? Is this function forwarding you to the success screen? That's kind of weird... seems to me that the accountService.registerUser should return a promise, and the onSubmitClick should resolve the promise and forward the user.
Try forwarding back to the RegistrationController at different points in the code, and try to narrow down the exact point that it becomes undefined. I think that you have some code running somewhere that you don't think you do.

In Angular, can view be loaded in code?

Very simply, after an API call, depending on the return value, how is the appropriate view loaded? Consider having
search.html
views/found.html
views/notfound.html
Search's controller makes an AJAX call to a service and gets a good or bad result. Now I want the appropriate view to load, without user having to click. I just can't figure out how to do this and have looked at scores of routing/view examples. I'm using HTML5 mode.
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'search.html',
controller: 'searchCtrl'
})
.when('found', {
templateUrl: 'views/found.html',
controller: 'foundCtrl'
})
.when('notFound', {
templateUrl: 'views/notFound.html',
controller: 'notFoundCtrl'
})
.otherwise({
templateUrl: 'search.html',
controller: 'searchCtrl'
});
$locationProvider.html5Mode({
enabled: true,
requiredBase: true
});
And in the controller ..
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
'found';
return true;
}).error(function (error) {
// how is the view/route loaded without a user click?
'notFound';
return false;
});
I'm just lost after getting back the response on how to invoke a view within the template.
Since you are using ngRoute use $location.path() instead of $state.go(). The $location.path() method accepts a url specified in route configuration. E.g.:
$location.path('/found');
Say your controller is AppController, then the complete code will look something like:
angular.module('app', ['ngRoute'])
.controller('AppController', function ($location, $http) {
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
$location.path('/found');
}).error(function (error) {
// how is the view/route loaded without a user click?
$location.path('/notFound');
});
});
Refer https://docs.angularjs.org/api/ng/service/$location for api documentation of $location.path

AngularAMD + ui-router + dynamic controller name?

I'm trying to write a generalized route in my application and resolve the view and controller names on the fly based on the route params.
I have the following code that works:
$stateProvider.state('default', angularAMD.route({
url: '/:module/:action?id',
templateUrl: function (params) {
var module = params.module;
var action = module + params.action.charAt(0).toUpperCase()
+ params.action.substr(1);
return 'app/views/' + module + '/' + action + 'View.html';
},
controller: 'userController',
}));
However, I'm unable to figure out a way to resolve the controller name dynamically. I tried using resolve as described here, but ui-router seems to handle resolve differently than angular-route.
Any pointers?
EDIT: I've already tried using controllerProvider but it doesn't work for me (for instance, the following code just returns a hard coded controller name to test whether it actually works):
controllerProvider: function () {
return 'userController';
}
Gives me the following error:
Error: [ng:areq] Argument 'userController' is not a function, got undefined
http://errors.angularjs.org/1.3.3/ng/areq?p0=userController&p1=not%20aNaNunction%2C%20got%20undefined
This is a link to working plunker.
solution
We need two features of the UI-Router:
resolve (to load the missing pieces of js code)
controllerProvider (see cites from documentation below)
angularAMD - main.js definition
This would be our main.js, which contains smart conversion controllerName - controllerPath:
require.config({
//baseUrl: "js/scripts",
baseUrl: "",
// alias libraries paths
paths: {
"angular": "angular",
"ui-router": "angular-ui-router",
"angularAMD": "angularAMD",
"DefaultCtrl": "Controller_Default",
"OtherCtrl": "Controller_Other",
},
shim: {
"angularAMD": ["angular"],
"ui-router": ["angular"],
},
deps: ['app']
});
controllers:
// Controller_Default.js
define(['app'], function (app) {
app.controller('DefaultCtrl', function ($scope) {
$scope.title = "from default";
});
});
// Controller_Other.js
define(['app'], function (app) {
app.controller('OtherCtrl', function ($scope) {
$scope.title = "from other";
});
});
app.js
Firstly we would need some method converting the param (e.g. id) into controller name. For our test purposes let's use this naive implementation:
var controllerNameByParams = function($stateParams)
{
// naive example of dynamic controller name mining
// from incoming state params
var controller = "OtherCtrl";
if ($stateParams.id === 1) {
controller = "DefaultCtrl";
}
return controller;
}
.state()
And that would be finally our state definition
$stateProvider
.state("default", angularAMD.route({
url: "/{id:int}",
templateProvider: function($stateParams)
{
if ($stateParams.id === 1)
{
return "<div>ONE - Hallo {{title}}</div>";
}
return "<div>TWO - Hallo {{title}}</div>";
},
resolve: {
loadController: ['$q', '$stateParams',
function ($q, $stateParams)
{
// get the controller name === here as a path to Controller_Name.js
// which is set in main.js path {}
var controllerName = controllerNameByParams($stateParams);
var deferred = $q.defer();
require([controllerName], function () { deferred.resolve(); });
return deferred.promise;
}]
},
controllerProvider: function ($stateParams)
{
// get the controller name === here as a dynamic controller Name
var controllerName = controllerNameByParams($stateParams);
return controllerName;
},
}));
Check it here, in this working example
documentation
As documented here: $stateProvider, for a state(name, stateConfig) we can use controller and controllerProvider. Some extract from documentation:
controllerProvider
...
controller (optional) stringfunction
Controller fn that should be associated with newly related scope or the name of a registered controller if passed as a string. Optionally, the ControllerAs may be declared here.
controller: "MyRegisteredController"
controller:
"MyRegisteredController as fooCtrl"}
controller: function($scope, MyService) {
$scope.data = MyService.getData(); }
controllerProvider (optional) function
Injectable provider function that returns the actual controller or string.
controllerProvider:
function(MyResolveData) {
if (MyResolveData.foo)
return "FooCtrl"
else if (MyResolveData.bar)
return "BarCtrl";
else return function($scope) {
$scope.baz = "Qux";
}
}
...
resolve
resolve (optional) object
An optional map<string, function> of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them ALL to be resolved before the controller is instantiated...
I.e. let's use controllerProvider:
... to resolve the controller name dynamically...
In case, that you managed to get here, maybe you'd like to check another similar solution with RequireJS - angular-ui-router with requirejs, lazy loading of controller

Angular router resolve results in an unknown provider error

I am trying to use Angular's routing to resolve the necessary objects for the controller scope. I have read a few tutorials on how to do this but I still get an Unknown Provider error. The issue seems to be with project being injected into ProjectDetailCtrl.
app.js
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config( function ($interpolateProvider, $routeProvider) {
$routeProvider
...
.when('/project/:projectId', {
templateUrl : 'partials/_project_detail.html',
controller: 'ProjectDetailCtrl',
resolve: {
project: function ($route, MyService) {
return MyService.get('projects/', $route.current.params.projectId).then(function(data) {
console.log('VERIFY DATA: ', data);
return data;
});
}
}
controllers.js
.controller('ProjectDetailCtrl', function ($scope, project) {
$scope.project = project;
}
Edit
services.js
.factory('MyService', function ($http, $q) {
var MyService = {
...
get: function (items_url, objId) {
var defer = $q.defer();
$http({method: 'GET',
url: api_url + items_url + objId}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
Edit 2
The issue is apparently not with the Service method, as this also produces the error:
app.js
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config( function ($interpolateProvider, $routeProvider) {
$routeProvider
...
.when('/project/:projectId', {
templateUrl : 'partials/_project_detail.html',
controller: 'ProjectDetailCtrl',
resolve: {
project: {title: 'foo'}
}
});
})
I can verify my resolve function is being returned properly, but Angular still complains that project is unidentified. What is this issue here? I have tried making my controllers into a module and passing that to the myApp module, but I still get the same Unidentified Provider issue for project.
Note: I am using Angular 1.2.9.
Edit 3: solution
So the issue was this line in my template:
<!-- WRONG: <div ng-controller="ProjectDetailCtrl">-->
<div>
<h2 ng-show="project">Project: <strong>{{ project.title }}</strong></h2>
</div>
Apparently the ng-controller directive cannot be use with resolve.
You forgot to add ngRoute as a dependency for your module. Thats why $routeProvider and $route service are undefined.
Update:
See this example. Problem was in ng-controller directive
You're returning the MyService.get, which is a promise, and then within the result of the promise, you're returning the data.... but to what?
You want to return the promise, but not the original promise... so you create your own promise using $q, and Angular will wait and resolve it for you before loading your route.
project: function ($route, MyService) {
var deferred = $q.defer();
MyService.get('projects/', $route.current.params.projectId).then(function(data) {
console.log('VERIFY DATA: ', data);
deferred.resolve(data);
});
return deferred.promise;
}
Or, assuming MyService.get returns a promise, you should be able to just do
project: function ($route, MyService) {
return MyService.get('projects/', $route.current.params.projectId);
}
And obviously inject $q into config
This question has been asked before, therefore it's a possible duplicate.
The top answer points out usage of controllers within markup to have caused this.
Search your codebase (markup or templates to be exact) for the term ng-controller.
Verify if there is a matching controller, as in this case ProjectDetailCtrl
Remove it from the markup
It solved the problem in my case.

Using resolve in $routeProvider causes 'Unknown provider ...'

I am trying to do an asynchronous http request to load some data before my app loads and so I am using a resolve in $routeProvider which is an http request in my MainController. For some reason, I keep getting Error: [$injector:unpr] Unknown provider: appDataProvider <- appData where appData is where I do my http request. I am using AngularJS v 1.2.5.
Here is the code and two methods that I tried that both give the same error:
Method #1
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(appData.data);
}
];
MainController.loadData = {
appData: function($http, $location, MainFactory){
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}
};
app.js
var app = angular.module('HAY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: MainController.loadData
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
I tried changing the name in case it was a conflicting system reserved keyword but with no luck. For some reason, appData is never recognized
Method #2
I also tried changing it around like so:
app.js
var app = angular.module('HEY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: {
appData: ['$http', '$location','MainFactory', function($http, $location, MainFactory) {
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}]
}
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(resolvedData);
}
];
However, the result was exactly the same. Does this have something to do with angular 1.2.5 ?
Here is a working version from someone else
http://mhevery.github.io/angular-phonecat/app/#/phones
And here is the code:
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone) {
return Phone.query();
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve}).
otherwise({redirectTo: '/phones'});
}]);
Here's an example of the code I've used in the application I'm working on, not sure it will help much because its not much different than how you have it already.
Routing
.when('/view/proposal/:id',{
controller : 'viewProposalCtrl',
templateURL : 'tmpls/get/proposal/view',
resolve : viewProposalCtrl.resolveViewProposal
})
Controller
var viewProposalCtrl = angular.module('proposal.controllers')
.controller('viewProposalCtrl',['$scope','contacts','details','rationale',
function($scope,contacts,details,rationale){
$scope.contacts = contacts;
$scope.details = details;
$scope.rationale = rationale;
// [ REST OF CONTROLLER CODE ]
});
// proposalSrv is a factory service
viewProposalCtrl.resolveViewProposal = {
contacts : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Contacts',$route.current.params.id)
.then(function(data){
return data.data.contacts;
},function(){
return [];
});
}],
details : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Details',$route.current.params.id)
.then(function(data){
return data.data.details;
},function(){
return {};
});
}],
rationale : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Rationale',$route.current.params.id)
.then(function(data){
return data.data.rationale;
},function(){
return {};
]
}]
};
Now that I think about it, when I was developing my application I did have a problem and not sure why when I named my resolve function "resolve." This gave me a problem:
.when('/path',{
// stuff here
resolve : myCtrlr.resolve
})
but this did not:
.when('/path',{
//stuff here
resolve : myCtrlr.myResolveFn
})
Another Possibility
The only other thing I can think of, is that you're returning the promise from the $http call and then trying to use appData.data Try using the .then function or one of the other functions (.success,.error) to retrieve the information from the promise.
The problem was NOT due to previously using different version of AngularJS.
Here are the fixes using the code that I have above.
In app.js, you need to declare the controller as controller: 'MainController' and NOT as controller: MainController even though you have var MainController = app.controller('MainController', ....).
Second and biggest thing was that in my index.html I declared my controller already like so:
index.html
body ng-app="HEY" controller="MainController" /body
This was causing the whole Unknown provider error Apparently angular wont tell you that you have already declared the controller that you are using to do the resolve it and that that will cause a weird error that have nothing to do with the resolve.
I hope this helps someone who may have the same problem.
One thing I noticed in angular 1x docs is that YOU DO NOT SPECIFY THE RESOLVED PARAMETER AS AN ANNOTATED DEPENDENCY
So this:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
'resolvedFromRouter'
Controller
]
function Controller($scope, someService, resolvedFromRouter) {
// <= unknown provider "resolvedFromRouter"
}
is wrong. You don't specify the resolved parameter as a dependency, in the docs:
For easier access to the resolved dependencies from the template, the resolve map will be available on the scope of the route, under $resolve (by default) or a custom name specified by the resolveAs property (see below). This can be particularly useful, when working with components as route templates.
So just do this instead:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
Controller
]
function Controller($scope, someService) {
$scope.$resolve.resolvedFromRouter; // <= injected here
}

Resources