Angular - Unknown Provider from Provider - javascript

I have the strange issue, that somehow my own provider is not injecting correctly into my app.
This is my provider:
angular.module '1425App'
.provider 'OData',[() ->
#_baseUrl = ''
return {
setBaseUrl: (value) ->
#_baseUrl = value
return
$get: ['$http', '$q', ($http, $q) ->
return {
getAll: (resource) ->
dfd = $q.defer()
$http.get("#{#_baseUrl}/#{resource}").success (res) ->
console.log res
dfd.resolve()
return
return dfd.promise
}
]
}
]
This is my app + config block:
angular.module('1425App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'angular-loading-bar',
'ngAnimate',
'toaster',
'ui.gravatar',
'ngFitText',
'google-maps',
'mm.foundation',
'restangular',
'ui.select2',
'ngTable',
'ngGrid',
'ngCsv',
'ui.date',
'ngDragDrop',
'ui.sortable'
])
.config ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, cfpLoadingBarProvider, baseUrl, ODataProvider) ->
$httpProvider.interceptors.push('httpInterceptor')
ODataProvider.setBaseUrl(baseUrl + '/odata/')
cfpLoadingBarProvider.includeSpinner = false
...
Im getting following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module
1425App due to: Error: [$injector:unpr] Unknown provider:
ODataProvider
This leads to my believe, that its an issue with injecting the provider into my app. Any idea what im missing?

Looking at you pasted snippet issue could be that you have config block appearing before oData provider has been registered. Try setting up the config block after the oDataProvider registration.
Separate out config block from app registration and load it after your provider(s) have been registered. You can only configure the providers that are registered before the specific config block that uses it. This is not the case with constant though you can have them registered in any order.
The above information (which was a bug) is as of 1.2.* version of angular, with 1.3 you can register providers even after the config block.

Related

Using $httpBackend in developement

In my Angular application I want to use $httpBackend to fake the data while development(and not while testing). The problem with using it while development is that all the requests initiated to fetch the static resources like template html or css fails with it.
angular.js:14516 Error: [$compile:tpload] Failed to load template: views/login.html (HTTP status: undefined undefined)(…)
As shown above after including the $httpBackend service to application it starts to complain about the http templates.
angular
.module('myApp', ['ngResource','ui.router','ngMockE2E'])
.config(function ($urlRouterProvider, $stateProvider) {
$stateProvider.state('dashboard.contacts',{
url: '/contacts/:id',
views:{
'mainWrapper':{
templateUrl: 'views/contacts.html',
controller:'ContactsCtrl as contactsctl'
}
},
});
})
.run(function ($state, $rootScope, AuthenticationService, $httpBackend) {
var contacts = [{'id':1,'name':'ABC','phone':1234},
{'id':2,'name':'DEF','phone':3456},
{'id':3,'name':'GHI','phone':5678}];
$rootScope.$state = $state;
if(!AuthenticationService.isAuthenticated()) {
$state.transitionTo('login');
}
$httpBackend.whenGET('/contacts').respond(contacts);
})
.controller('ContactsCtrl', function(){
var contactsctl = this;
});
What is best way to generate some fake data in angular application in BackendLess way while development ?

Need help setting up Karma (Getting an error)

I am new to Karma and would really appreciate any help understanding the reason for the error below:
Uncaught Error: [$injector:nomod] Module 'myApp.controllers' 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.
app.js
angular.module('myApp', [
'ngRoute',
'myApp.controllers',
'myApp.filters',
'myApp.services',
'myApp.directives'
]).
config(function ($routeProvider, $locationProvider) {
controllers.js
angular.module('myApp.controllers', []);
StoreCtrl.js
angular.module('myApp.controllers').
controller('StoreCtrl', ['$scope', '$http', function ($scope, $http) {
StoreCtrl.spec.js
describe('StoreCtrl', function() {
beforeEach(module('myApp.controllers'));
var $controller;
beforeEach(inject(function(_$controller_){
// The injector unwraps the underscores (_) from around the
// parameter names when matching
$controller = _$controller_;
}));
describe('$scope.filterByPrice', function() {
it('test spec', function() {
});
});
});
karma.conf.js
files: [
'public/js/scripts/angular/angular.js',
'public/js/scripts/angular-mocks/angular-mocks.js',
'public/js/scripts/angular-route/angular-route.min.js',
'public/js/app.js',
'public/js/controllers/*.js',
'tests/**/*.spec.js'
],
File Structure
Karma wasn't picking the controllers.js file before the StoreCtrl.js
I had to change the code below:
'public/js/controllers/*.js',
to
'public/js/controllers/controllers.js',
'public/js/controllers/StoreCtrl.js',
and it works now :)

Unknown provider in Karma test

I have the following provider:
(function (angular) {
angular.module('app')
.provider('$_Config', ConfigProvider);
function ConfigProvider() {
.... //routes definition
}
ConfigProvider.prototype.$get = function () {
return this;
};
ConfigProvider.prototype.getRoutes = function() {...}
//other prototype functions
})(angular);
In app.js I am using it like this:
app.config(function ($routeProvider, $_ConfigProvider) {
var routes = $_ConfigProvider.getRoutes();
routes.forEach(function(route) {
$routeProvider
.when(route.route, {
.....
})
}
Every thing work fine till it gets to testing. Here is my test:
describe('Provider: $_ConfigProvider', function () {
// load the providers module
beforeEach(module('app'));
// instantiate provider
var $_ConfigProvider;
beforeEach(inject(function (_$_Config_) {
$_ConfigProvider = _$_Config_;
}));
it('Should verify getRoutes function', function () {
var routes = $_ConfigProvider.getRoutes();
expect(Object.prototype.toString.call(routes) === '[object Array]').toBe(true);
});
});
When running the test I am getting the following error:
Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:unpr] Unknown provider: $_ConfigProvider
Note: The $_ConfigProvider is injected correctly during run-time.
You are likely not including the file where the provider is defined in in your karma.conf.js dependencies list. See this question:
Include dependencies in Karma test file for Angular app?
I would rename the $_Config to something else, '$' is usually reserved for angular-specific components.

Uncaught Error: [$injector:modulerr]

I have following app.js file for angular, and i want to add a response interceptor but when i add response interceptor it throws me an error on console
Uncaught Error: [$injector:modulerr]
Below is the file
(function () {
"use strict";
angular.module("builder").config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$provide","$httpProvider",
function ($stateProvider, $urlRouterProvider, $locationProvider, $provide, $httpProvider) {
$httpProvider.responseInterceptors.push('responseObserver');
}]).factory('responseObserver',
function responseObserver($q, $window) {
return function (promise) {
return promise.then(function (successResponse) {
return successResponse;
}, function (errorResponse) {
switch (errorResponse.status) {
case 401:
$window.location = $window.location;
break;
case 403:
$window.location = './403.html';
break;
case 500:
$window.location = './500.html';
}
return $q.reject(errorResponse);
});
};
});
}());
Can anyone guide me what is causing this issue.
You didn't define the angular module 'builder' anywhere. The following format (which your file uses):
angular.module("builder")
means, "use the angular module 'builder' which I have already defined."
The following format:
angular.module("builder",[])
means, "create the angular module 'builder' right here and now (and eliminate any previous one)".
You can create and use at the same time as:
angular.module("builder",[]).config(....
but you must define it somewhere at least once.
Your factory should be changed like below:
.factor('responseObserver', '$window', function responseObserver($window, $q){
});
notice the way I injected $window. You have to annotate the $window, so that injector can recognize the functions/directives/services to be injected.

AngularJS why can't I use share a provider with another module?

I have a App module that has many component modules that are injected into the App module. The App module has a provider that I would like to use inside of the component modules, but I am receiving an injector error: Error: $injector:modulerr Module Error
Here is what I am trying
var App = angular.module('App', [
'ngRoute',
'Blog',
'Media',
'Pages',
]);
App.provider('Core', function() {
this.baseDirectory = '/test';
this.$get = function() {
var baseDirectory = this.baseDirectory;
}
});
App.config(['$routeProvider', 'CoreProvider', function($routeProvider, CoreProvider) {
$routeProvider
.when(CoreProvider.baseDirectory + '/admin', {
templateUrl: baseUrl + '/backend/scripts/angular/index.html'
})
.otherwise({
template: ""
});
}]);
All of the above code works, its when I try to use the CoreProvider inside of another module, such as Blog (has been injected into App module)
var Blog = angular.module('Blog', ['ngRoute']);
Blog.config(['$routeProvider', 'CoreProvider', function($routeProvider, CoreProvider) {
$routeProvider
.when(CoreProvider.baseDirectory + '/admin/blog', {
templateUrl: CoreProvider.baseDirectory + '/blog/blog.html',
controller: 'BlogController'
});
}]);
I receive the error Error: $injector:modulerr Module Error and the Angular docs state that this error occurs when a module fails to load due to an exception.
Why can't I use CoreProvider inside of my Blog module?
If sharing a base directory is all you need, why not use a Constant?
var shared = angular.module('Shared',[]);
shared.constant('baseDirectory', '/test');
// Use the constant on your modules:
var module1 = angular.module('Module1', ['Shared']);
module1 .config(['baseDirectory', function(baseDirectory) {
console.log(baseDirectory + '/admin2');
}]);
var module2 = angular.module('Module2', ['Shared']);
module2.config(['baseDirectory', function(baseDirectory) {
console.log(baseDirectory + '/admina');
}]);
Here is a working plunkr: http://plnkr.co/edit/wktdqCMZuvDbk7sz1mMi?p=preview
I guess that this is a better practice, for more info please refer to: https://docs.angularjs.org/guide/providers

Categories