angular Uncaught ReferenceError: Service is not defined - javascript

I have the following component in which I am trying to inject a service:
angular.
module('phoneList').
component('phoneList', {
templateUrl: '/static/common/angular/phone-list/phone-list.template.html',
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
var self = this;
authenticationService.authenticate().then(function(){
console.log('it worked!!!!!!!!');
});
}
]
});
The service looks like this:
angular.module('authentication').factory('authenticationService', function($http, $se){
function authenticate(){
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
console.log('auth service: '+data['access_token']);
$sessionStorage.access_token = data['access_token'];
});
}
function getToken(){
return $sessionStorage.access_token;
}
return {
authenticate:authenticate,
getToken:getToken
};
});
My phone-list.module.js looks like this:
angular.module('phonecatApp', [
'phoneList',
'authentication',
]);
angular.module('phoneList', ['authentication']);
When I run this i get the error:
Uncaught ReferenceError: authenticationService is not defined
When I put 'authenticationService' in '', I get the error:
Error [$injector:unpr] authtenticationService

It seems the service isn't properly injected into the PhoneListController.
Change it to:
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
...
The strings in the array are just to keep the injected dependency references minification safe. The service still needs to be added as a function argument.
Also be sure to call angular.module once for each component:
app.module.js
angular.module('phonecatApp', [
'ngRoute',
'phoneList',
'authentication',
]);
phone-list.module.js
angular.module('phoneList', ['authentication']);

Related

Angular stateprovider resolve not passing data to controller

So I have a problem with angular ui.router, which apparently isn't passing the data from resolve to controller. I have the following state set up:
$stateProvider
.state('myState', {
url: "/myUrl",
templateUrl: "myTemplate",
controller: 'myController',
resolve: {
randomData: function($q, $sails) {
var defer = $q.defer();
$sails.get("/me")
.success(function(data) {
console.log(data) // prints out actual data
defer.resolve(data);
})
return defer.promise;
}
}
and in myController I basically have
myApp.controller('myController', [
'$scope', function ($scope, randomData) {
console.log("randomData:" + randomData)
// prints out 'randomData: undefined'
}
])
According to every doc, stackoverflow post and tutorial, this piece of code should work, but it keeps printing undefined. Does anyone have an idea why this isn't working?
You forgot to inject the data in the array notation:
myApp.controller('myController', [
'$scope', 'randomData', // <-- this one
function ($scope, randomData) {
console.log("randomData:" + randomData);
}
])

Creating a custom provider angularjs

I am trying to create some routing that will resolve calls to my rest api
before the page loads. Because I can't inject a service created using
app.factory(), I am attempting to create a provider to do this so I can use it in my config routing, but I'm
getting Error: [$injector:unpr] Unknown provider: $http
I want to be able to call the provider in mainFlow.api for 4 or five endpoints
that will resolve before the page loads. Am I going about this the correct way?
My code:
service.js
var mainApp = angular.module('mainApp');
mainApp.provider('choiceService', ['$http', function($http) {
return {
$get: function() {
return {
get: function(url) {
return $http.get(url);
}
};
}
};
}]);
config.js
var mainApp = angular.module('mainApp', [
'ui.router'
]);
mainApp.config(['$stateProvider', '$urlRouterProvider', '$choiceServiceProvider',
function($stateProvider, $urlRouterProvider, choiceServiceProvider) {
$stateProvider
.state('mainFlow', {
abstract: true,
url: '/base',
template: '<ui-view/>'
})
.state('mainFlow.choose-main', {
url: '',
templateUrl: '/choose_main.html',
})
.state('mainFlow.contact', {
controller: 'ContactFormController',
url: '/contact-details',
templateUrl: '/panel_contact_info.html',
})
.state('mainFlow.api', {
url: '/about-your-api',
controller: 'ApiFormController',
templateUrl: '/panel_about_your_api.html',
resolve: {
choice: function(choiceServiceProvider) {
return choiceServiceProvider.get('/api/yes-no-choice/');
},
other_choice: function(choiceServiceProvider){
return choiceServiceProvider.get('/api/my-other-choice/')
}
}
})
Then I can use the resolved data in controller.js
controller.js
var mainApp = angular.module('mainApp');
mainApp.controller('ApiFormController', [
'$scope',
'$state',
'choiceService',
function($scope, $state, choiceService) {
$scope.choices = choiceService;
}
]);
I was passing $http in service.js when there was no need. I was also passing in '$choiceServiceProvider' in config.js when it should have been just 'choiceServiceProvider'

accessing $router (ngNewRouter) inside function in module factory in Angular 1.4 doesn't work

I have the following:
angular.module('app', [ 'ngNewRouter', 'security',
and security module
angular.module('security', ['ngNewRouter'])
.factory('authService', ['$http', '$q', '$window', 'CONSTANTS', '$location', '$router', authService ]);
function authService($http, $q, $window, CONSTANTS, $location, $router) {
var service = {};
//tries to login user
var _login = function(loginData) {
var data = {
"email": loginData.email,
"password": loginData.password
};
$http.post(CONSTANTS.baseURL + '/login', data)
.success(function(data, status, headers, config) {
_authenticate(data);
--->>> $router and $location --->>> not defined here, although $http, $q, $window, CONSTANTS are defined
})
.error (function (data, status, headers, config) {
_logOut();
});
};
Why is $router and $location not defined inside that function, and the others are?
What am I missing?
I also tried defining security module with and without ngNewRouter

Error: [$injector:unpr] Unknown provider in jasmine test when routeprovider service is injected in a controller

I have created an application in angular js, in which i am using ng-view for navigating templates, from routeProvider i am injecting a service called customerDetail to all templates. when i wrote a jasmine testcase for injecting customerDetail services into the CustomerReportController constructor, but i am getting
<failure type="">Error: [$injector:unpr] Unknown provider: customerDetailProvider <- customerDetail
can anyone please tell me some solution for this
main/customerReport/main.spec.js
describe('tsi', function()
{
var $scope, customerDetail;
beforeEach(module('tsi.customerReport'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
CustomerReportController = $controller('CustomerReportController', {
$scope: $scope,
customerDetail: customerDetail
});
}));
it('test CustomerReportController', inject(function() {
expect(CustomerReportController).toBeTruthy();
}));
});
main.js
angular.module( 'tsi', ['tsi.customerDetail', 'ngRoute'])
.config(function(RestangularProvider, $routeProvider)
{
RestangularProvider.setBaseUrl('/customer/service/detail');
$routeProvider.when('/customerDetail',
{
templateUrl: 'main/main.tpl.html',
controller: 'CustomerDetailController',
resolve: {
customerDetail: function(CustomerDetailService) {
return CustomerDetailService.getServiceDetail();
}
}
}).when('/customerReport',
{
templateUrl: 'main/customerReport/main.tpl.html',
controller: 'CustomerReportController',
resolve: {
customerDetail: function(CustomerDetailService) {
return CustomerDetailService.getServiceDetail();
}
}
}).otherwise(
{
redirectTo: '/customerDetail'
});
})
.factory('CustomerDetailService', function(Restangular) {
return {
getCustomerDetail: function() {
return Restangular.one('user/customerDetail').get().then(function(customerDetail) {
return customerDetail;
});
}
};
});
main/customerReport/main.js
angular.module('tsi.customerReport', [])
.controller('CustomerReportController', function($scope, $http, $filter, $timeout, customerDetail)
{
$scope.customerOrderDetails = customerDetail;
:
:
});
the same problem faced by me..
what I did was that I included all the services there in my js file. make sure all the services and providers are injected properly
here is an example code for jasmine unit testing.
describe('UserService',function() {
var scope, DataService, UserService, http, cookieStore;
beforeEach(module('app'));
beforeEach(inject(function ($http, _DataService_) {
http = $http;
DataService = _DataService_;
}));
it('getProfilePicture', function () {
http.post('/api/getProfilePicture', function (data) {
expect(data).toBeDefined();
});
});
});
DataService is my service here

AngularJS: Load templateUrl after all data received by the controller

I'd like to display my template when the data coming from my server are loaded.
I created a module called Services with inside some services to load my data, I'm using HomeService for my example.
var app = angular.module('MyApp', ['Services']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'home.html',
controller: 'Home_Ctrl',
resolve: {
loadData: //??
}
});
}]);
app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
$scope.data = HomeService.getData();
}
I guess I need to create a promise to do that. Is it possible to put this function inside my controller?
I mean, I don't want something like that:
var ctrl = app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
//Do something
}
//Promise
ctrl.fct = function($q) {
}
I want something like that:
app.controller('Home_Ctrl', ['$scope', '$q', 'HomeService', function($scope, $q, HomeService) {
//Do something
//Promise
this.fct = function() {}
}
Any idea?
Thanks.
You could use resolve property of controller.
You could create a object which will return promise and assign to controller resolve function and inject the same in controller definition kindly see very simple example
$routeProvider.when('/ExitPoll', {
templateUrl: '/partials/ExitPoll.html', controller: exitpollController, resolve: {
responseData: ['$http', function ($http) {
return $http.get('/Candidate/GetExitPolls/hissar').then(function (response) {
return response.data;
});
}],
}
});
var exitpollController = ['$scope', '$http','responseData','$rootScope',
function ($scope, $http, responseData, $rootScope) {
}];

Categories