AngularJS: route.resolve in ES6 - angularjs

I am trying to refactor an existing Angular-Project to use ES6-Modules and import statements. This works for the majority of the application, but the resolve blocks in my routes are giving me trouble.
As far as I can tell the syntax should be the same as before:
$stateProvider.state('stateName'), {
template: <div></div>
controller: 'stateCtrl'
controllerAs: 'ctrl'
resolve: {
someData: ['DataService', function(DataService){
return DataService.getData();
}]
}
}
However setting a breakpoint in someData tells me that my 'DataService' is not resolved properly by angulars dependency injection (or rather: it is resolved properly, but was not initialized yet). The service gets registered on the according module, but its constructor did not get called before entering the someData-function.
Since i thought that i got the syntax wrong i experimented a bit and found that some other Services (created with the same syntax and registered on the same module as the DataService) are actually initialized and injected properly within the resolve-block.
Do you have any idea where to look or how i can troubleshoot this?

If you're using ES6, it should be like this:
/* #ngInject */
export default function config($stateProvider) {
resolve: {
/* #ngInject */
someData: (DataService) => DataService.getData()
}
}
To read a little more about ngInject see the ng-annotate github page. It does the injections for you.

Related

Unit Testing AngularJS 'config' Written in TypeScript using Jasmine

I'm currently trying to Unit Test the config of a new AngularJS component. We are using ui-router to handle the routing in our application. We have been able to successfully test it for all our previous components, but the code for all of them was written in plain Javascript. Now that we switched to TypeScript we are having some issues.
This is the TypeScript code where we make the configuration of the module:
'use strict';
// #ngInject
class StatetiworkpaperConfig {
constructor(private $stateProvider: ng.ui.IStateProvider) {
this.config();
}
private config() {
this.$stateProvider
.state('oit.stateticolumnar.stateticolumnarworkpaper', {
url: '/stateticolumnarworkpaper',
params: { tabToLoad: null, groupTabId: null, jurisdiction: null, showOnlyItemsWithValues: false, showOnlyEditableItems: false},
template: '<stateticolumnarworkpaper-component active-tab-code="$ctrl.activeTabCode"></stateticolumnarworkpaper-component>',
component: 'stateticolumnarworkpaperComponent',
resolve: {
onLoad: this.resolves
}
});
}
//#ngInject
private resolves($q, $stateParams, ColumnarWorkpaperModel, ChooseTasksModel, localStorageService) {
// Some not important code
}
}
angular
.module('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper')
.config(["$stateProvider", ($stateProvider) => {
return new StatetiworkpaperConfig($stateProvider);
}]);
This is the Spec file, which is written in Javascript:
describe('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper', function () {
beforeEach(module('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper'));
beforeEach(module('oit'));
var state = 'oit.stateticolumnar.stateticolumnarworkpaper';
it('has a route', inject(function ($state) {
var route = $state.get(state);
expect(route.url).toBe('/stateticolumnarworkpaper');
}));
});
My issue is when executing the line var route = $state.get(state), as the route variable is always null. I could verify that the config() method is being executed, but I'm simply out of ideas as to why route is always null on my test.
Just for reference, this is the configuration of another component, but using Javascript
'use strict';
angular
.module('oit.components.binders.binder.dom_tas.taxaccountingsystem.stateworkpapers.stateworkpapersreview')
.config(stateworkpapersreviewConfig);
function stateworkpapersreviewConfig($stateProvider) {
$stateProvider
.state('oit.binder.taxaccountingsystem.stateworkpapersreview', {
url: '/stateworkpapersreview?reviewType&binderId&year&jurisdiction&chartId&withBalance',
templateUrl: 'components/binders/binder/dom_tas/taxaccountingsystem/stateworkpapers/stateworkpapersreview/stateworkpapersreview.tpl.html',
controller: 'StateworkpapersreviewController',
controllerAs: 'stateworkpapersreviewCtrl',
resolve: {
onLoad: resolves
}
});
function resolves($q, $stateParams, StateTiBinderJurisdictionsModel, WorkpaperModel, localStorageService, StateTiFiltersModel) {
// Some not important code
}
}
As you can see the code is basically the same, but still, I can successfully test this component's config in the way I described, but when I try with the one written in TypeScript I get the error I mentioned.
PD: I'm aware of several similar posts (like this one), but none of them deal with TypeScript, which is my issue.
There is huge difference between the TS snippet and the JS one.
I’m not sure why you are using a class to elite a function? .config suppose to get a function.
You can write the same code as in JS just with .ts suffix, it is a valid TS code.
Then you just can import that config function, pass it all the injectables and test it.

How is it that we cannot inject a service into a configuration block but can do so in a resolve?

I am basically following a tutorial and wanted to understand why this code works.
This is my service:
app.factory('postFactory', ['$http', function($http){
var obj= {
postList:[]
};
obj.getAll= function(){
return $http.get('/posts').success(function(data){
angular.copy(data, obj.postList);
});
};
return obj;`enter code here`
}]);
This is the resolve:
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
posts: function(postFactory){
return postFactory.getAll();
};
)
The resolve calls the method getAll() on postFactory. I know that a resolve is reached in the code before the controller is initialized and therefore, the service. How does it then access the method at all? Also, as stated in this question and answer, AngularJS dependency injection of value inside of module.config,
A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
So if we want to 'prevent accidental instantiation of services before they have been fully configured', why are we being able to instantiate them in the resolve?

Is there a way that I can simplify an angular-ui-router resolve?

I already have done this:
resolve: {
required_data: function($q, testService) {
return $q.all([
testService.getAdminTestLevel(),
testService.getAdminTestStatus(),
testService.getAdminTestType()
])
}
}
Is it possible for me to code this without the required_data just by connecting the function to the resolve: ?
No. The angular-ui-router wiki says,
The resolve property is a map object.
This was probably chosen to make resolved data easily accessible on the route. It works that way in both ngRoute and ui-router.
You could simplify by making what you have in the function be a method of testService, then running function(testService), { return testService.doAdminChecks(); } or similar.

Use angular compileProvider outside config block

I'm trying to create directives on the fly, actually I achived that, but seams pretty hacky.
This was my first approach:
function create(myDir) {
angular.module("app").directive(myDir.name, function() {
return {
template:myDir.template
};
});
}
It didn't work because you can't register directives after application started.
based on this post: http://weblogs.thinktecture.com/pawel/2014/07/angularjs-dynamic-directives.html
I found out that I could use compileProvider to do the work, but since compileProvider isn't available outside config block, you need to put it out, so I did:
var provider = {};
angular.module("app",[]);
angular.module('app')
.config(function ($compileProvider) {
//It feels hacky to me too.
angular.copy($compileProvider, provider);
});
....
function create(myDir) {
provider.directive.apply(null, [myDir.name, function () {
return { template: myDir.template } }]);
render(myDir); //This render a new instance of my new directive
}
Surprisingly it worked. But I can't feel like being hacking the compileProvider, because I'm using it not in the way it was suppose to be, I would really like to know if is it possible to use the compileProvider properly after the application has started.
There is a list of dependencies that can be injected to config blocks (these are built-in $provide, $injector and all service providers) and a list of dependencies that can be injected to everywhere else (service instances and good old $injector). As you can see all that constant does is adding the dependency to both lists.
A common recipe for using providers outside config is
app.config(function ($provide, $compileProvider) {
$provide.constant('$compileProvider', $compileProvider);
});

routeprovider using resolve to pass value to controller

I'm looking for a way to pass a value to my controller from my appRoutes. With the idea for it to call a function and do some magic. heres some code so you get an idea:
appRoutes.js
$routeProvider
.when('/students/some/path/:id', {
templateUrl: 'views/studentRecord.html',
controller: 'StudentsController',
resolve: { myVar: 'test' }
});
studentsCtrl.js
angular.module('StudentsCtrl', [])
.controller('StudentsController', function($scope, $http, $routeParams,
$location, myVar, Students) {
/* ... */
});
Ideally, I'd like to call a given function within this controller - but parsing a value would be just as good. The idea is that the controller handles all pages to do with 'students' and will make some http calls so my node server will do some calls to mongodb. Ive tried a few variations on the internet and with no luck. I got an error:
Error: $injector:unpr Unknown Provider
but I'm not sure how to resolve it.
EDIT: I've half resolved this now by using this; http://plnkr.co/edit/mSb58e8cGDNYU27xSizk?p=preview
ideally i'd like to separate the app.js into controllers and services - currently working on this, any edit of the plnkr would be great.
Question still stands of is it possible to hit a function within the controller first, rather than resolving one through a service?
In each resolve property, you can have a function that lets Angular inject services for you to use:
resolve: {
myVar1: function(testService) { return testService.fetchList1(); },
myVar2: function(anotherService, $http) {
// call service functions to mongo-db or what have you
return result;
}
}
Then, your controller, just inject the properties:
// myVar1 and myVar2 are now here
app.controller('StudentsController', function($scope, myVar1, myVar2) {
/* ... */
});
If the returned value from the function inside resolve is a promise, then it will be resolved before controller code is called (hence, the name resolve). This is actually the recommended approach as it makes service code (such as testService) reusable across many controllers.
Passing a function that returns the value
.state('tab2', {
url: '/tab2',
templateUrl: 'templates/tab2.html',
controller: 'Tab2Controller as tab2Ctrl',
//promise
resolve: {
lastName: function () { return 'makarov'}
}
});
Then in the controller
function Tab2Controller(lastName) {
console.log("Tab2", lastName);
}

Resources