I would like to attach a string from a service to every request. Attempt:
'use strict';
angular.module('main')
.service('Foo', function () {
self.bar = 'haz';
})
.run(function ($injector, Foo) {
$injector.get('$http').defaults.transformRequest = function (data, headersGetter) {
headersGetter()['X-Bar'] = Foo.bar;
};
});
Error: [$injector:nomod] Module 'Foo' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Note: I'm using ui-router and have multiple files; but one module; if that makes a difference.
Be sure to have ng-app="main" somewhere in your HTML because definitely the error message says that you are trying to load a module Foo...
Next, your approach is almost right. First, what should self be in the Foo service - use this. And also, why do you use the $injector? Just inject $http directly... your code then is as follows:
angular.module('main')
.service('Foo', function () {
this.bar = 'haz';
})
.run(function ($http, Foo) {
$http.defaults.transformRequest = function (data, headersGetter) {
headersGetter()['X-Bar'] = Foo.bar;
};
});
My $injector approach was taken from: http://engineering.talis.com/articles/elegant-api-auth-angular-js/
Looking at the docs: https://docs.angularjs.org/api/ng/service/$http, here's how I rewrote it:
angular.module('main')
.service('Foo', function () {
this.bar = 'haz';
})
.run(function ($injector, Foo) {
$injector.get('$http').defaults.headers.common['X-Bar'] = Foo.bar;
});
Which works fine. Also, looks like I had another bug in my code which was causing the issue… that's the problem with coding at midnight >.<
Related
When i try to create angularjs module in usual way, it works perfect, but when i try to execute same code inside a callback function of aync function call, it throws error that module not found:
The following code works fine:
var myApp = angular.module('SSApp',[]);
myApp.controller('config', function($scope) {
});
But following throws error:
Init_Data(function() {
initApp();
});
function initApp() {
var myApp = angular.module('SSApp',[]);
myApp.controller('config', function($scope) {
});
}
function Init_Data(callback) {
chrome.storage.local.get(null, function(data) {
window.data = data;
callback();
});
}
I've defined ng-app="SSApp" directive in respective html code.
The reason your code is not doing what you expect is because, Angular tries to bootstrap the module "SSApp" automatically when the DOM is ready. But, finds no such module defined by your JavaScript code when it tries to do so.
You probably have ng-app="SSApp" somewhere in your HTML which is why Angular tries to bootstrap the module automatically.
You can choose to bootstrap the module manually by removing the ng-app directive and doing
angular.bootstrap(document.documentElement, ['SSApp']);
This is the change you have to do:
var myApp = angular.module("SSApp", []);
Init_Data(function () {
initApp();
});
function initApp() {
myApp.controller('config', function ($scope) {
});
console.log(myApp)
}
function Init_Data(callback) {
setTimeout(function () {
callback();
},4000);
}
From what I understand in your code, first you want to load data and then to add config controller to your app...so define your app first and then in your callback configure
I have this piece of code:
.service('webSocket', function ($rootScope, socketFactory, CONFIG, $timeout) {
angular.element(document).ready(function () {
$rootScope.log('Waiting for connection...',CONSOLE_INFO);
});
And I am getting this error:
TypeError: $rootScope.log is not a function
This service is injected into this controller:
.controller('mainCtrl', function mainCtrl($scope, $rootScope, webSocket, myConsole ...
In which I have:
$rootScope.log = function (msg, type) { myConsole.log(msg,type); ... };
Can you tell me where is the problem? Or at least point me in the right direction? The reason I am using document ready function is because apart from logging messages to browser console (console.log) I use notifications for user (pNotify library) which needs to be called after DOM is loaded.
Sharing something between services using $rootScope should be considered generally as anti-pattern. If you don't have some different implementation of console for different controllers, you can do it Angular-way and perform all configurations in config block. Subscribing to document ready event in the service is also not a good idea (I would prefer to do it in run block), since in angular service is instantiated once it is first time required by any other service or controller or whatever. In order to have configurable service that may have different console implementation I would implement it using provider as follows:
angular.module('app',[]).
constant('console', console).
constant('PNotify', PNotify).
provider('myConsole', function() {
var log = angular.noop;
function MyConsoleFactory() {
return {
log: log,
debug: log
}
}
this.setLog = function(logImplementation) {
log = logImplementation
}
this.$get = [MyConsoleFactory];
}).
config(['myConsoleProvider', 'console', 'PNotify', function(myConsoleProvider, console, PNotify) {
myConsoleProvider.setLog(function(msg) {
console.log('[LOG] '+ Date.now() + ':\t' + msg);
new PNotify({
title: 'Title',
text: msg
});
});
}]).
run(['myConsole', '$document', function(myConsole, $document) {
$document.ready(function () {
myConsole.log('Waiting for connection...');
});
}]);
In this case you don't need any controller at all.
Plunker: http://plnkr.co/edit/aV9TIO07pnDs26xDBPtf?p=preview
That happens because service code runs before service was added to controller(where $rootScope.log method is defined). You can move $rootScope.log = function (msg, type) { myConsole.log(msg,type); ... }; into app.run(...) method and it will work.
Very new to Angular testing... using 1.3.0.rc0. To get started I'm trying to do something simple: get the value of a constant I set. Within a config.js, I have the following:
(function () {
'use strict';
var app = angular.module('app');
// create app configuration
var appConfig = {
version = '0.0.1.0',
debugMode = true
};
app.constant('config', appConfig);
app.config([function ($logProvider, config) {
// set the debugging setting of the app > same setting for the app
if ($logProvider.debugEnabled) {
$logProvider.debugEnabled(config.debugMode);
}
}]);
})();
I'm tried numerous things to write my tests (using jasmine & karma), but I keep getting an error that:
Error: [$injector:modulerr] Failed to instantiate module app due to:
TypeError: 'undefined' is not an object (evaluating '$logProvider.debugEnabled').
I get that this was a bug a while ago in the angular-mocks.js file but has since been resolved. Regardless, no matter the test I write, it doesn't work. Here's what i'm working with now, knowing that there are issues with it.
'use strict';
describe('config.js', function () {
var logProvider;
beforeEach(module(inject(function ($log) {
logProvider = $log;
})));
beforeEach(module('app', logProvider));
it('should set the config constant to the app global configuration settings', function () {
var $injector = angular.injector(['ng', 'app']);
var settings = $injector.get('config');
//var settings = inject(config);
expect(settings.debugMode).toBe(true);
});
});
Am I doing this right? If so, is there no way to get around the test issue with $logProvider?
There is much to learn about how modules work in Angular, especially under testing with ngMocks. I'll try to be brief.
One always begins by calling module (from ngMocks) one (or more times) to build up the module "cookbook" for a test run.
In any of these module calls you have an opportunity to access and stash away a previously defined provider.
The first time you call inject (from ngMocks) in a given test path, the module "cookbook" is "baked" for that path and the injector is populated based on recipes in that "cookbook".
Subsequent calls to module are irrelevant. Your expression beforeEach(module('app', logProvider)); executes too late (even if it did what you wanted, which it would not).
In fact, I'm surprised that you didn't get the error: "Error: Injector already created, can not register a module!".
inject always returns the thing created by the provider, never the provider itself. Your first beforeEach ...
beforeEach(module(inject(function ($log) {
logProvider = $log;
})));
... actually sets logProvider to the $log service, not the $logProvider.
Does this help?
Here is a sample from my forthcoming course on Ng testing that shows how to access a provider (in this case, the $logProvider). It was inspired by your question.
First, the config2 constant (I already had a value called config:
// my sample application module definition is called 'basics'
var basics = angular.module('basics', []);
/* define 'config2' constant - which is available in Ng's config phase */
basics.constant('config2', {
debugMode: true
});
// use constant in config phase
basics.config(function ($logProvider, config2) {
$logProvider.debugEnabled(config2.debugMode);
})
Now the spec (using Mocha and Chai):
describe('Basics - constant:', function() {
'use strict';
beforeEach(module('basics'));
// other stuff
describe("the $logProvider", function(){
var configConstant;
var $log;
var $logProvider;
beforeEach(module(
// Could combine with module('basics') definition in outer describe
// but only need it here in this describe
// This module definition function has access to any previously defined provider
// which in this case is any provider defined in ng, ngMocks, or basics
function( _$logProvider_) {
$logProvider = _$logProvider_;
}
));
// inject triggers injector creation; module definition now "baked"
beforeEach(inject(function(config2, _$log_){
configConstant = config2;
$log = _$log_;
}));
it("is accessible via the module function", function(){
expect($logProvider).to.exist;
});
it("is not the same as the log service", function(){
expect($logProvider).not.to.equal($log);
});
it("has same debugEnabled value as config2.debugMode", function(){
expect($logProvider.debugEnabled()).to.equal(configConstant.debugMode);
});
});
});
Perhaps this is a terrible idea, but if it is then please tell me why and then pretend that it's an academic exercise that won't see the light of day in production.
I'd like to add some logic to the Angular $injector service, to monitor when certain services are injected into other services. Since it seems that Angular provides a mechanism for decorating services, I thought this would be the way to go. However, the following code throws an error.
(function () {
'use strict';
var app = angular.module('app');
app.config(['$provide', function ($provide) {
$provide.decorator('$injector', ['$log', '$delegate', addLoggingToInjector]);
}]);
function addLoggingToInjector($log, $delegate) {
var baseInstantiate = $delegate.instantiate;
var baseInvoke = $delegate.invoke;
$delegate.instantiate = function (type, locals) {
// $log.debug('Calling $injector.instantiate');
baseInstantiate(type, locals);
};
$delegate.invoke = function (fn, self, locals) {
// $log.debug('Calling $injector.invoke');
baseInvoke(fn, self, locals);
};
return $delegate;
};
})();
The specific error is:
Uncaught Error: [$injector:modulerr] Failed to instantiate module app
due to: Error: [$injector:unpr] Unknown provider: $injectorProvider
The answer is: no.
$provide.decorator is used to intercept service creation -- that is why it is called from .config block, when there is still time to configure all services, as none of them has been created. $provide.decorator basically gets the Provider of the service and swaps its $get with newly delivered decorFn.
$injector is not like other services. It is created, as the very first step of bootstrapping an application -- way before app.config is called. [look at functions: bootstrap and createInjector in angular source code]
But hey, you can achieve your goal quite easily by tweaking the source code just a bit :-) Particularly look at function invoke(fn, self, locals).
UPDATE I got some inspiration from #KayakDave. You actually do not have to dig in the source-code itself. You can use the following pattern to observe each call to any of $injector methods:
app.config(['$injector', function ($injector) {
$injector.proper =
{
get : $injector.get,
invoke : $injector.invoke,
instantiate : $injector.instantiate,
annotate : $injector.annotate,
has : $injector.has
}
function getDecorator(serviceName)
{
console.log("injector GET: ", serviceName);
return this.proper.get(serviceName);
}
function invokeDecorator(fn, self, locals)
{
console.log("injector INVOKE: ", fn, self, locals);
return this.proper.invoke(fn, self, locals);
}
function instantiateDecorator(Type, locals)
{
console.log("injector INSTANTIATE: ", Type, locals);
return this.proper.instantiate(Type, locals);
}
function annotateDecorator (fn)
{
console.log("injector ANNOTATE: ", fn);
return this.proper.annotate(fn);
}
function hasDecorator(name)
{
console.log("injector HAS: ", name);
return this.proper.has(name);
}
$injector.get = getDecorator;
$injector.invoke = invokeDecorator;
$injector.instantiate = instantiateDecorator;
$injector.annotate = annotateDecorator;
$injector.has = hasDecorator;
}]);
PLNKR
You can't use the Angular decorator service on $injector. As Artur notes $injector is a bit different from other services. But we can create our own decorator.
Why we can't use Angular's decorator
At the code level the issue is that $injector doesn't have a constructor function- there's no $injectorProvider.
For example both of these return true:
$injector.has('$location');
$injector.has('$locationProvider')
However, while this returns true:
$injector.has('$injector')
this returns false:
$injector.has('$injectorProvider')
We see the importance when we look at the Angular decorator function:
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
And
providerSuffix = 'Provider'
So the Angular decorator expects to operate on the service's constructor (serviceName + providerSuffix). Pragmatically, since we don't have an $injectorProvider we can't use decorator.
Solution
What we can do is override the Angular injector's get function ourselves by replacing the injector's default get with one that calls the original, Angular defined, get followed by our function.
We'll apply this to $injector rather than the nonexistent $injectorProvider like so:
app.config(['$provide','$injector', function ($provide,$injector) {
// The function we'll add to the injector
myFunc = function () {
console.log("injector called ", arguments);
};
// Get a copy of the injector's get function
var origProvider = $injector,
origGet = origProvider.get;
//Override injector's get with our own
origProvider.get = function() {
// Call the original get function
var returnValue = origGet.apply(this, arguments);
// Call our function
myFunc.apply(this,arguments);
return returnValue;
}
}]);
You'll see the provider being injected is the first augment, so app.value('aValue', 'something'); yields the following log statement:
injector called ["aValueProvider"]
Demo fiddle
I saw some sample code here Delaying AngularJS route change until model loaded to prevent flicker
And straight away I though this was the right way to go, I need to have my controller LOAD only when a resolve is finished loading, normally most of the examples around tell you to put the code under resolve in the routeprovder as an inline function, but this sounds wrong. The controller needs it so why not have the controller implement the function to resolve. This sounded just what I was looking for ie. This seems to use the prototype pattern ??
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone, $q) {
// see: https://groups.google.com/forum/?fromgroups=#!topic/angular/DGf7yyD4Oc4
var deferred = $q.defer();
Phone.query(function(successData) {
deferred.resolve(successData);
}, function(errorData) {
deferred.reject(); // you could optionally pass error data here
});
return deferred.promise;
}
}
Problem is I have my controller like so
'use strict';
angular.module('TestApp')
.controller('ItemsCtrl', function ($scope) {
});
So how do I apply a new function on the controller when my controller is declared inside a module ?
What I really need is something like
TestCtrl.resolve = {
items: function( $q) {
..........
return deferred.promise;
}
}
This then would allow me to have in my routeprovider..
when('/items', {
templateUrl: 'views/items.html',
controller: 'TestCtrl',
resolve: 'TestCtrl.resolve'}). // Need to use ' around resolve?
But I am confused how I would get this to work ?
I would really love any feedback, I am at a loss.
Not possible to define like 'TestCtrl.resolve' if you want to use resolve with .controller syntax then you have to define inline within route provider . The advantage of inline resolve in routeprovider is that you can reuse controller easily but using same controller and changing the logic in resolve function
You can also use a service:
resolve: {data : function(service) {
return service.getData();
}}