AngularJS - Unknown provider: AuthProvider - javascript

I am trying to redirect users to a login page if they make an attempt to access pages that require them to be logged in. I am using Firebase and AngularJS, following this guide. The error explanation on the AngularJS site indicates that either a non-existent definition or duplicate definition is causing the issue but I cannot identify either of these in my code. Additionally, the stack trace of the error doesn't indicate which of my files caused the error, only mentioning the angular.js file.
Can anyone give me some insight as to what is causing this issue?
Note: The site runs without errors and users can log in and out if I leave out the resolve section of the $routeProvider.
Here is my app.js
angular.module('richWebApp', ['ngRoute', 'firebase', 'objectFilter'])
.constant('fb', {
url: 'https://<my-firebase-app>.firebaseio.com/' //name removed for security reasons
})
.run(function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
if(error === "AUTH_REQUIRED") {
$location.path("/login");
}
});
})
.config(function($routeProvider){
$routeProvider.
when('/login', {
templateUrl: 'pages/login/login.html'
}).
when('/main', {
templateUrl: 'pages/main/main.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
when('/thread/:threadId', {
templateUrl: 'pages/thread/thread.html',
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireAuth();
}]
}
}).
otherwise({
redirectTo: '/login'
});
});
Here is the main.js controller
angular.module('richWebApp')
.controller('mainPageController', function($scope, $location, userService, currentAuth, threadService, fb, $firebaseAuth, $filter){
$scope.user = userService.getLoggedInUser();
$scope.newThreadTitle = '';
$scope.threadSubject = ''
$scope.createNewThread = false;
$scope.sortBy = 'dateAdded'
$scope.threads = threadService.getAllThreads();
$scope.getSubjects = function(subject) {
return $scope.threads.subject;
}
$scope.beginAddThread = function() {
$scope.createNewThread = true;
}
$scope.addThread = function(){
if(!$scope.newThreadTitle || !$scope.newThreadSubject){
return false;
}
var date = new Date();
var newThread = {
title: $scope.newThreadTitle,
subject: $scope.newThreadSubject,
username: $scope.user.name,
numComments: 0,
comments: [],
dateAdded: date.getTime()
};
$scope.threads.$add(newThread);
$scope.newThread = '';
$scope.newThreadTitle = '';
$scope.newThreadSubject = '';
$scope.createNewThread = false;
}
$scope.sortByDate = function() {
$scope.sortBy = 'dateAdded';
}
$scope.sortByPopularity = function() {
$scope.sortBy = 'numComments';
}
$scope.searchSubject = function(subject) {
$scope.searchThread = subject;
}
$scope.logout = function(){
userService.logout();
}
});
Here is the thread.js controller
angular.module('richWebApp')
.controller('threadPageController', function($scope, $location, $routeParams, $filter, currentAuth, threadService, fb, userService){
var threadId = $routeParams.threadId;
$scope.newComment = '';
var thread = threadService.getThread(threadId);
thread.$bindTo($scope, 'thread')
$scope.addComment= function(){
if(!$scope.newComment){
return false;
}
var currentUser = userService.getLoggedInUser();
var date = new Date();
var newComment = {
text: $scope.newComment,
username: currentUser.name,
dateAdded: date.getTime(),
userPic: currentUser.profilePic
};
$scope.thread.comments = $scope.thread.comments || [];
$scope.thread.comments.push(newComment);
$scope.thread.numComments += 1;
$scope.newComment = '';
}
});

Your code is referring to an Auth factory, which is shown in the example under Retrieving Authentication State. Include this in your code.
.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("<YOUR FIREBASE>");
return $firebaseAuth(ref);
}
]);

Related

unknown provider factoryprovider <- factory <- controller angular js

I am having problem while injecting dependency from service to controller. Although i added it but still same error of
Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl
I basically need to render a ng-view to my index.html
Index.html
<div ng-view>
</div>
app.js
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'app/views/list.html', controller: 'listCtrl'
}).
otherwise({
redirectTo: '/list'
});
}]);
websiteService.js
app.factory('webiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
/* application services that would not return values */
app.service('websiteService', ['$http', function ($http) {
//service for pagination
this.paginate = function ($scope) {
//pagination code
$scope.currentPage = 1;
$scope.totalItems = $scope.model.length;
$scope.numPerPage = 10;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.model.indexOf(value);
return (begin <= index && index < end);
};
//ordering code
$scope.reverse = true;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
}
//service to change state of a website
this.changeSiteState = function (website) {
var newState = website.State == "Stopped" ? "Started" : "Stopped";
$http({
method: 'POST',
url: '/Replicate/ChangeState/',
data: JSON.stringify({ webName: website.Name, state: newState }),
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
if (data == "success") {
website.State = website.State == "Stopped" ? "Started" : "Stopped";
}
else {
alert(data);
}
}).error(function (data, status, headers, config) {
alert(data);
});
}
}])
listCtrl.js
app.controller('listCtrl', function websiteCtrl($scope, $location, websiteFactory, websiteService, $modal) {
//function triggered at the intialization of controller
$scope.init = function () {
$scope.model = [];
setTimeout(function () {
websiteFactory.getAllWebsites().success(function (data) {
$scope.model = data;
websiteService.paginate($scope);
})
}, 0);
};
//delegation of change state to service method
$scope.changeState = function (website) {
websiteService.changeSiteState(website);
}
//open modal and shows details of single object
$scope.showDetails = function (websiteName) {
var modalInstance = $modal.open({
templateUrl: '../Views/Replicate/Details.html',
controller: 'DetailsCtrl',
resolve: {
obj: function () {
return websiteFactory.getFilteredObject($scope.model, websiteName);
}
}
});
}
});
You have misspelled "websiteFactory". In your factory definition code it is "webiteFactory" but in controller you are fetching it with different name using "websiteFactory" that's why it is not able to find this provider and producing error:
change:
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
That error comes when your factory is not registered with angular . Change it to
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
...do something here...
}

Retrieving cookie with every load of Single Page App

What specific changes need to be made to the AngularJS code below to check for the existence of a cookie named myCookie every time a page is loaded, and then to set the $rootScope.myCookieValue variable to become the value of myCookie?
The code is from the sample app whose complete code you can explore at this link. It is a very simple example app, and I just want a simple working solution to this so that I can build up more complex approaches from it.
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs : 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).controller('navigation',
function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function() {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function($http) {
var self = this;
$http.get('resource/').then(function(response) {
self.greeting = response.data;
})
});
you can do it in run block I guess:
angular.module('hello', ['ngCookies', 'ngRoute'])
.config(function ($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'home',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).run(function ($rootScope, $cookies) {
var cookieValue = $cookies.get("myCookie");
if (cookieValue) {
$rootScope.myCookieVar = cookieValue;
}
}).controller('navigation',
function ($rootScope, $http, $location, $route) {
var self = this;
self.tab = function (route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function (response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function () {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function () {
$http.post('logout', {}).finally(function () {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function ($http) {
var self = this;
$http.get('resource/').then(function (response) {
self.greeting = response.data;
})
});
I think you should use angular version > 1.4.x
you should also add reference angular-cookies.js

Pubnub chat in Angular

I'm implementing the pubnub chat in my AngularJS application. I'm following this tutorial
The problem is that if I create a new AngularJS application from scratch the chat works, but if I implement the code in my already existing application I get this error:
Missing Callback pubnub.min.js:1
And I can't see messages that I write and messages that I should receive but I can send them and I can see those messages on the other side of the chat.
Do you know how can I solve this problem?
EDIT: this is the controller for the pubnub chat:
'use strict';
angular.module('myApp.appointments', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
}])
.controller('appointmentsCtrl', ["$rootScope", "$scope", "$http", "$timeout", "$cookies", "URL", "Pubnub", function($rootScope, $scope, $http, $timeout, $cookies, URL, Pubnub) {
$scope.sortType = 'name';
$scope.sortReverse = false;
$scope.sortType_s = 'time';
$scope.filterAppointments = false;
$scope.filterDate = '';
$scope.highlightRow = '';
$scope.$on('$routeChangeSuccess', function() {
var data = {
"token":$cookies.get('userToken'),
"hairdresser_id": $cookies.get('userId')
};
$http.post(URL.url + 'appointments', data).then(function(res){
$scope.app_list = res.data.appointments;
$scope.service_list = res.data.appointment_services;
$scope.customers_list = res.data.customers;
$scope.pending_number = res.data.pending;
});
data = {
"token":$cookies.get('userToken'),
"hairdresser_id": $cookies.get('userId')
};
$http.post(URL.url + 'monthly_earnings', data).then(function(res){
$rootScope.monthly_earnings = res.data.amount;
});
});
// Pubnub implementation
$scope.channel = "messages-channel";
$scope.uuid = _.random(100).toString();
Pubnub.init({
publish_key: MY_KEY,
subscribe_key: SUB_KEY,
ssl: true,
uuid: $scope.uuid
});
$scope.sendMessage = function() {
if (!$scope.messageContent || $scope.messageContent === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
console.log(m);
}
});
$scope.messageContent = '';
}
$scope.messages = [];
Pubnub.subscribe({
channel: $scope.channel,
triggerEvent: ['callback']
});
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function(ngEvent, m) {
$scope.apply(function() {
$scope.messages.push(m)
});
});
}]);
You forgot the s at the end of the triggerEvents statement in the Pubub.subscribe function :
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback']
});
Let me know if it has solved your issue.

AngularJS Uncaught Error: [$injector:modulerr] Failed to instantiate module

I am following this angular, jquery, bootstrap pagination tutorial http://jsfiddle.net/ef0d9zuk/1/ that I found through a related post. The tutorial example works yet I am receiving a error message Uncaught Error: [$injector:modulerr] Failed to instantiate module GithubIssues due to:
Error: [$injector:modulerr] Failed to instantiate module Pages due to:
Error: [$injector:nomod] Module 'Pages' 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.
Can anyone tell me what I am doing wrong here?
var defaultPage = angular.module('GithubIssues', [
'ngRoute',
'DefaultPage'
]);
defaultPage.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/default', {
templateUrl: 'partials/default.html',
controller: 'DefaultController'
}).
when('/issues/:issueId', {
templateUrl: 'partials/issues.html',
controller: 'IssuesController'
}).
otherwise({
redirectTo: '/default'
});
}]);
// declaring my DefaultController for default page and params
defaultPage = angular.module('DefaultPage', ['pages']);
angular.module('pages', []).factory('Pages', function () {
return {
getPage: function (pageNum) {
var pageData = $scope.ctrl.info + pageNum;
}
return pageData;
}
});
defaultPage.controller('DefaultController', ['$scope', '$http', 'Pages', function ($scope, $http, Pages) {
$scope.data = {};
var url = 'https://api.github.com/repos/npm/npm/issues'
$http.get(url, {
headers: {
'Content-type': 'application/json'
}
}).success(function (data) {
$scope.ctrl.info = data;
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.numberOfPages = function () {
return 25;
};
$scope.data = Pages.getPage($scope.currentPage);
$scope.getPage = function (pageNum) {
$scope.data = Pages.getPage(pageNum);
}
/* $scope.itemsPerPage = 26;
$scope.currentPage = 1;*/
/*$scope.makeTodos = function() {
$scope.GithubIssues = [];
for (var i = 1; i <= $scope.ctrl.info.length; i++) {
$scope.GithubIssues.push({ $scope.ctrl.info, done:false});
}
};*/
/* $scope.figureOutTodosToDisplay = function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
var end = begin + $scope.itemsPerPage;
$scope.ctrl.info = $scope.ctrl.info.slice(begin, end);
console.log(data);
; };*/
/*$scope.makeTodos();*/
/*$scope.figureOutTodosToDisplay();
$scope.pageChanged = function() {
$scope.figureOutTodosToDisplay();
};*/
});
}]); //defaultPage ctrl end
defaultPage.filter('startFrom', function () {
return function (input, start) {
start = +start;
return input.slice(start);
}
});
// declaring my IssuesController for my issues page and params
defaultPage.controller('IssuesController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$http.get('https://api.github.com/repos/npm/npm/issues')
.success(function (data) {
$scope.ctrl = data;
$scope.whichIssue = $routeParams.issueId;
//Issue page previous issue button
if ($routeParams.issueId > 0) {
$scope.prevIssue = Number($routeParams.issueId) - 1;
} else {
$scope.prevIssue = $scope.ctrl.length - 1;
}
//Issue page next issue button
if ($routeParams.issueId < $scope.ctrl.length - 1) {
$scope.nextIssue = Number($routeParams.issueId) + 1;
} else {
$scope.nextIssue = 0;
}
});
}]); // end
Removing the line
defaultPage = angular.module('DefaultPage', ['pages']);
and changing 'DefaultPage' dependency to 'pages' at
var defaultPage = angular.module('GithubIssues', [
'ngRoute',
'DefaultPage'
]);
will resolve dependency errors. The reason for error is defaultPage name is used twice for two different module.
Seem to be injecting a dependency before registering it
Change order of:
defaultPage = angular.module('DefaultPage', ['pages']);
angular.module('pages', []).factory('Pages', function () {
return {
getPage: function (pageNum) {
var pageData = $scope.ctrl.info + pageNum;
}
return pageData;
}
});
To
angular.module('pages', []).factory('Pages', function () {
return {
getPage: function (pageNum) {
var pageData = $scope.ctrl.info + pageNum;
}
return pageData;
}
});
defaultPage = angular.module('DefaultPage', ['pages']);

AngularJS controller is not a function

I can't find the mistake in my application.
The error stack that i receive is this one:
Error: [ng:areq] Argument 'RepoController' is not a function, got undefined
Here is the code of app.js
(function() {
var app = angular.module('gitHubViewer',["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.when("/user/:username", {
templateUrl: "user.html",
controller: "UserController"
})
.when("/repo/:usermane/:reponame", {
templateUrl: "repo.html",
controller: "RepoController"
})
.otherwise({
redirectTo:"/main"
});
});
}());
here is the code of the controller
(function() {
var module = angular.module('gitHubViewer');
var RepoController = function($scope, github, $routeParams) {
var onRepoDetailsComplete = function(data) {
$scope.issues = data;
github.getRepoCotributors($score.username, $scope.reponame).then(onRepoCotributorsComplete,onError);
};
var onRepoCotributorsComplete = function(data) {
$scope.repoContribuors = data;
};
var onError = function(reason) {
$scope.error = reason;
}
$scope.username = $routeParams.username;
$scope.reponame = $routeParams.reponame;
github.getRepoDetails($score.username, $scope.reponame).then(onRepoDetailsComplete,onError);
};
module.controller('RepoController',["$scope","github","$routeParams",RepoController]);
}());
Can you please have a look becuase I really can't find teh mistake that I made.
Regards
Fabio
Where does "$score.username" come from?
github.getRepoDetails($score.username, $scope.reponame)
I think that you are missing a dependency for the $score or you have just misspelled $scope.

Categories