Unkown provider: $urlMatcherFactory
This is the error message that Angular throws when I try to inject $urlMatcherFactory in the app config.
I have included the ui-router JS file and have been using it for last few months.
I need to do something like this:
var dateMatcher = $urlMatcherFactory.compile("/day/{start:date}");
$stateProvider.state('calendar.day', {
url: dateMatcher
});
as this example shows.
Normally code like this won't identify $urlMatcherFactory. So I tried injecting it as a dependency on the config but then I get this error.
In this Q&A Matching url with array list of words in AngularJS ui-router you can see how to use the $urlMatcherFactory. Also a link to working plunker .
In that example, the $urlMatcherFactory is used in the .run():
.run(['$urlMatcherFactory',
function($urlMatcherFactory) {
var sourceList= ['John', 'Paul', 'George', 'Ringo']
var names = sourceList.join('|');
var urlMatcher = $urlMatcherFactory.compile("/{source:(?:" + names + ")}/:id");
$stateProviderRef
.state('names', {
url: urlMatcher,
templateUrl: 'tpl.root.html',
controller: 'MyCtrl'
});
}
]);
And that would also mean, that if you are about to use it in a config phase, you should ask for
$urlMatcherFactoryProvider (see the Provider at the end)
BUT: using providers in a config phase means - we can configure them. I mean configure the provider itself. To be later evaluable (already configured) in run phase
Configuring Providers
You may be wondering why anyone would bother to set up a full-fledged provider with the provide method if factory, value, etc. are so much easier. The answer is that providers allow a lot of configuration. We've already mentioned that when you create a service via the provider (or any of the shortcuts Angular gives you), you create a new provider that defines how that service is constructed. What I didn't mention is that these providers can be injected into config sections of your application so you can interact with them!
First, Angular runs your application in two-phases--the config and run phases. The config phase, as we've seen, is where you can set up any providers as necessary. This is also where directives, controllers, filters, and the like get set up. The run phase, as you might guess, is where Angular actually compiles your DOM and starts up your app.
Related
I am building a single page application using angular. We use Continuous Integration with several Dev and QA environments. This means that every time I deploy the app in a different environment I need to update some config parameters such as SPA baseUrl, rest api url or url for my oauth server.
To achieve this, our CI engine generates a config.json file with the correct parameters for each environment when we are about to deploy there. To get this I have created a really simple service:
(function () {
'use strict';
angular
.module('app.core')
.factory('config', config);
config.$inject = ['$http'];
function config($http) {
return {
load: load
};
//////////
function load() {
return $http.get('assets/config/config.json');
}
}
}());
Most of my services are configured through providers during the config phase. And here is where the problem comes up. As you know, services cannot be injected during this phase but I would like to use config service to set up my providers with the correct URLs and parameters.
Is there a proper way to do this?
The only thing I can consider so far is having these config parameters embed in my module creation file so they are there ready to use. It seems quite ugly since I donĀ“t want any external process to my app modifying my source code.
If these are asynchronous services that rely on config.json, it is perfectly ok to change the way they are configured and fit your config into async workflow, e.g.
app.factory('config', function ($http) {
return $http.get('config.json', { cache: true })
.then(function (response) {
return response.data;
});
});
app.factory('asyncService', function ($http, config) {
return config.then(function (config) {
return $http...
}).then(...);
});
Otherwise the best option is to build json config to a service with Gulp/Grunt/whatever.
Think of
angular.module('config', []).constant('config', <%= configJson %>);
as of a compiled template rather than 'external process to my app modifying my source code'.
What I am doing at the moment (but I am open for a better solution) is to have a separate config file with the json object that contains all the config info.
Example of the file content:
var appConfigInfo = {
DEV: true,
API_PATH: 'your_custom_url'
// etc.
};
Then I add it as a constant in my app. Example:
angular
.module('app', [])
.constant('APP_CONFIG', appConfigInfo);
Now you can access all your configuration values via the constant. Don't forget to inject it in your controllers, etc.
I hope it helps.
I have two files in which I define services in my angular app, but when I try to use them both in my directive, I get an error saying the service provider is not found for whichever directive I define second. It seems like one service is overwriting the other. If I change the module definition in service2.js to myapp.services2, then it works. I would think I could add multiple factories to the same module this way. Can someone point out what I'm doing incorrectly?
service1.js:
var services = angular.module('myapp.services',[]);
services.factory('Service1', function() {
// service code
});
service2.js:
var services = angular.module('myapp.services',[]);
services.factory('Service2', function() {
// service code
});
mydirective.js:
angular.module('myappdirective', []).directive('myapp', ['Service1', 'Service2',
function(service1,service2) {
// directive code
}]);
This is from the docs:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
Found here:
https://docs.angularjs.org/guide/module
This is possible, however will be error prone, hence not recommended
Make small modification to what you are already doing
Just do not re-declare the module variable in other files other than service1.js or put the module definition to a file of its own and include these JS file in the order of Module.js, services.js, directive.js then it will work
I have a dependency injection (understanding) problem while testing a directive (AjaxLoader displayed only when there is a pending request).
App declaration :
angular.module('app', [
'directives.ajaxLoader',
'services.httpRequestTracker',
[...]
])
Directive code :
angular.module('directives.ajaxLoader', [])
.directive('ajaxLoader', ['httpRequestTracker',
function(httpRequestTracker) {
return {
templateUrl: 'common/ajaxLoader.tpl.html',
link: function($scope) { // This function can have more parameters after $scope, $element, $attrs, $controller
$scope.hasPendingRequests = function() {
return httpRequestTracker.hasPendingRequests();
};
}
};
}
])
Test code :
describe('ajaxLoader', function() {
beforeEach(function() {
module('directives.ajaxLoader', 'common/ajaxLoader.tpl.html');
});
describe('ajaxLoader directive', function() {});
});
From there, my directive works perfectly well in the browser, but tests fails with an error like :
Error: [$injector:unpr] Unknown provider: httpRequestTrackerProvider
<- httpRequestTracker <- ajaxLoaderDirective
Ok, so I need to inject my dependency somewhere. I have two solutions :
in my directive directly :
angular.module('directives.ajaxLoader', [
'services.httpRequestTracker'
])
in my test code directly :
beforeEach(function() {
module('directives.ajaxLoader', 'common/ajaxLoader.tpl.html', 'services.httpRequestTracker');
});
Both works, but I don't understand which one is the better and why ? And why is it working in my browser from the start and fails in my test ? In both case, all my directives and trackers are injected in my main app declaration
Thanks
Loading modules
It works in your application because services.httpRequestTracker is loaded. you did that by declaring it as a dependency of the main app module (your first code snippet).
However, when you test things, you want to mock everything that is not being tested to avoid biass. In your case, what if you had a problem in services.httpRequestTracker? ajaxLoader might be fine but your tests will fail.
Mocking
To mock everything else, you have two options:
spies (e.g. this http://angular-tips.com/blog/2014/03/introduction-to-unit-test-spies/ )
use dependency injection to substitute components
To use a dependency, you have to load the module with module().
you will have to load the dependency, but this might have a mock implementation.
Dependency Injection
Dependency injection lets you decouple classes. There is a service locator to resolve dependencies by name. That is, you say attribute a of class C is of type 'animal' (a string!). The service locator in the angular core finds which component implements it. A way of determining this is by looking up the loaded modules (e.g. dependencies of the main app module).
You didn't define any of this in your testing area (but it isn't a problem!). Karma uses a file karma.conf that contains a list of files to use. You might use this file to add libraries or mocked components.
With your particular problem:
The directive depends on httpRequestTracker. If you don't inject it there, it won't work (so it's ok).
In your test, you have to load both. That's why the first time it failed and the second it worked. However, instead of loading httpRequestTracker, I'd load a mock implementation of it.
I'm trying to use a vertxbus module. It's configuration is set using .value.
How do I update these configuration values from my 'appModule'?
To my understanding
angular.module('knalli.angular-vertxbus')
should return a reference to the module and .value should change the injected value.
I've created a jsFiddle and here is the js used:
'use strict';
var testmodule = angular.module('TestModule', []).value('key', 'module').value('key', 'module2');
testmodule.factory('MyService', ['key', function (key) {
return key;
}]);
var module = angular.module('myApp', ['TestModule'])
.run(function () {
testmodule.value('key', 'run1');
angular.module('TestModule').value('key', 'run2');
}).controller('MyCtrl', ['$scope', 'MyService', 'key', function ($scope, MyService, key) {
$scope.value = MyService;
$scope.key = key;
}]);
I would expect a result of run2 or at least run1 but module2 is returned. Why?
The actual idea behind .value, .constant or more generally .config is the possibility to change how the modules' components should constructed themselves.
In that case, the angular-translate's vertxBus component will invoke implicitly a SockJS instance which connects implicitly to a server. That means the configuration settings must be known before the application will be running. Because of this, there are two phases (see answer by Ilan Frumer): config and run.
However, because .value and .config are too static and could collide with other components, the angular module angular-vertxbus has an own provider for all the settings (since version 0.5: https://github.com/knalli/angular-vertxbus/releases/tag/v0.5.0).
Starting with 0.5, this could be look like this:
var module = angular.module('app', ['knalli.vertx-eventbus']);
module.config(function(vertxEventBus) {
vertxEventBus.useDebug(true).useUrlPath('/eventbus');
});
Just like the others, the provider is only available in the config-phase.
Disclaimer: I'm the author of angular-vertxbus
$provide shorthands
Under the hood, constant & value & service & factory & provider are all shorthands for the $provide service which is available only during the configuration phase.
From angular.js documentation:
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.
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
your case:
You cannot register providers (in your case value) inside run blocks because they are only available during the configuration phase.
Read more about modules and $provide
i've made an reusable module for angularJS. The module is manipulating templates inside the run function. Before its gets fully initialized i need to set various properties. In which function should i expose this properties ?
In my Angular-1.2 apps to configure the ngRoute's service I use a config block like this
app.config(function ($routeProvider) {
$routeProvider....
});
I think you could do the same by adding a service provider into your module.
Another solution would be to make your run block depend on a constant that would be defined from your application.
// In your module
foo.run(function (fooConfig) {
var url = fooConfig.url;
...
});
// In your app
app.constant('fooConfig', { url: ... });
Both solutions are demoed here : http://jsfiddle.net/JQ4Gm/
I should expose my "properties" inside a provider and access them inside config. Usage of provider.