Unknown Provider - AngularJS - angularjs

I have seen a lot of topic like that, but i didn't find solution.
I'm getting this error Error:
$injector:unpr Unknown Provider
Unknown provider: restaurantsProvider <- restaurants <- restaurantsController
Here is my controller:
(function () {
'use strict';
angular
.module('myApp')
.controller('restaurantsController', restaurantsController);
restaurantsController.$inject = ['$scope', 'restaurants'];
function restaurantsController($scope, restaurants) {
$scope.restaurants = restaurants.query();
}
})();
And service file:
(function () {
'use strict';
var restaurantsService = angular.module('restaurantsService', ['ngResource']);
restaurantsService.factory('restaurantsService', ['$resource', function ($resource) {
return $resource('/api/restaurants', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
If it affects on something, I'm using ASP.NET.

That error indicates that you are trying to inject something that angular doesn't know about. There are a few issues I'm seeing with your app structure which are leading to this issue...
You never actually declare your "myApp" module which is where you need to inject your restaurantService app.
Your controller takes in a 'restaurant' dependency but the service is actually called 'restaurantsService'
I would expect the app structure to look something like this:
(function () {
'use strict';
var restaurantsServiceApp = angular.module('restaurantsServiceApp', ['ngResource']);
restaurantsServiceApp.factory('restaurantsService', ['$resource', function ($resource) {
return $resource('/api/restaurants', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
(function () {
'use strict';
var myApp = angular.module('myApp', ['restaurantsServiceApp']);
myApp.controller('restaurantsController', restaurantsController);
restaurantsController.$inject = ['$scope', 'restaurantsService'];
function restaurantsController($scope, restaurantsService) {
$scope.restaurants = restaurantsService.query();
}
})();
Your serviceApp needs to be declared prior to it being injected in the other app.

Related

How to declare an AngularJs service with no parameters?

This works:
'use strict';
angular.module('MyApp').service('searchControllerPersistentData', ['$state', function ($state)
{
const Self = this;
}]);
but this gives an error in the controller where I try to inject the service:
'use strict';
angular.module('MyApp').service('searchControllerPersistentData', ['', function ()
{
const Self = this;
}]);
The service will not need anything injected into it. How do I declare it?
Just remove the brackets :
angular.module('MyApp').service('searchControllerPersistentData', function ()
{
const Self = this;
});

Restangular ignores setBaseUrl

The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});

How to pass initialization data to angular module?

I have a webmethod on my remote server returning a JSon object.
Said json object contains strings which are required for the module to proper work.
So, is there a way to pass something to an angular module?
An idea could be to perform an http request inside of the initialization of the module:
$scope.init = function(){
$http.get ()
...
then(){
$scope.mydata = result;
}
};
But that would be asynchronous...
If you are worried about the async nature of an HTTP request to fill out your $scope.mydata variable, then you need to include this in a RESOLVE in your route.
I'm using UI-ROUTER in my current project:
(function() {
'use strict';
angular
.module('capps.core')
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home.capps', {
url: '/',
template: '<ui-view/>',
data: {
requireLogin: true
},
resolve:{
resolveFunction: resolveFunction
}
});
}
]);
resolveFunction['$inject'] = ['$http'];
function resolveFunction($http) {
return $http.get(API_URL)
.then(function(res) {
console.log(res);
});
}
})();
Then in your controller, you can pass 'resolveFunction' as a dependency... then use that to assign to your $scope.myData.
...
angular.controller('myController', myController);
myController.$inject = ['resolveFunction', '$scope'];
function myController(resolveFunction, $scope) {
$scope.mydata = resolveFunction.data;
console.log(mydata);
};

Angular service injection using RequireJS

I'm using AngularAMD + RequirsJS for a single page app and I'm having some issues when injecting a service in the app.js file.
Here the code:
login_service.js
define(['app'], function(app) {
'use strict';
app.service('loginService', function($location, $state, Restangular) {
return {
login: function(data, scope) {},
logout: function() {},
isLogged: function() {}
}
});
});
app.js
define(['angularAMD', 'restangular', 'angular-ui-router'], function(angularAMD) {
'use strict';
var app = angular.module('MyApp', ['restangular', 'ui.router', 'loginService']);
app.run(function($rootScope, $state, $stateParams, $location, loginService) {
console.log(loginService)
/*
Error: [$injector:modulerr] Failed to instantiate module MyApp due to: [$injector:modulerr]
Failed to instantiate module loginService due to:
$injector:nomod] Module 'loginService' is not available! You either misspelled the module name or forgot to load it.
*/
});
app.config(function($stateProvider, $urlRouterProvider, $i18nextProvider, RestangularProvider) {
});
});
I would liked to access the loginService in the run function but can't as I keep getting the "Failed to instantiate module MyApp" error message.
I've tried to load the login service file as follow:
define(['angularAMD', 'restangular', 'angular-ui-router', 'services/login_service'], function(angularAMD) {
});
But then I have another error stating that app is undefined in the Login Service.
Thank you very much for your helps.
David
It is happeing because 'loginService' is not a module it's a service and you cannot add 'loginService' (service) to the module you can only add only module to another module.
you can do one thing :-
var app = angular.module('loginService',[]);
app.service('loginService', function($location, $state, Restangular) {
return {
login: function(data, scope) {},
logout: function() {},
isLogged: function() {}
}
});
Ps:- I am not sure about this :-P
The problem is caused by the fact that requireJS loads the files dynamically and this assures you that the files are already loaded before it runs the code.
You should do the following:
Remove the ng-app from your html
Use a manual bootstrapping:
angular.element().ready(function(){
angular.bootstrap(document,['MyApp']);
});

Angular Modal Cannot Resolve From Factory

I have an AngularJS factory which I am attempting to use to create modals. However, when I attempt to use the resolve method in the $modal my modal instance controller gets an unresolved provider.
Here is how I am calling my factory from my controller:
var modalOptions = {
template: 'app/common/modalwindow.html',
data: data
};
modalFactory.openModal(modalOptions);
My modal factory is simple for now, all it has is a single open modal method:
(function() {
'use strict';
var factoryId = 'modalFactory';
angular.module('app').factory(factoryId, ['$modal', modalFactory]);
function modalFactory($modal) {
var factory = {
openModal: openModal
}
return factory;
function openModal(data) {
$modal.open({
templateUrl: data.template,
controller: 'modalInstanceCtrl',
resolve: {
modalData: function () {
return data.data;
}
}
});
}
}
})();
However, when my modalInstanceCtrl is called it throws an error. Here is my modalInstanceCtrl
(function () {
'use strict';
var controllerId = 'modalInstanceCtrl';
angular.module('app').controller(controllerId, ['common', 'modalData', modalInstanceCtrl]);
function modalInstanceCtrl(common, modalData) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
log(modalData);
};
})();
The error it throws is:
Unknown provider: modalDataProvider <- modalData <- modalInstanceCtrl
I thought the resolve in the $modal would handle this injection. Am I assuming wrong here?

Resources