Uncaught Error: [$injector:modulerr] In Firebase Authentication - javascript

I have developed a small task for Gmail user login and logout using firebase authentication. I've faced an issue on my code Uncaught Error: [$injector:modulerr]
I've added the below libraries:
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
And initialized the firebase config.
index.html
<html ng-app="appName">
<body ng-controller="loginCtrl">
<div id="message">
<button ng-click="googleSignin()">SignIn into App</button>
</div>
<p id="load">Firebase SDK Loading…</p>
</body>
When we click the sign in button it will show Gmail authentication popup after complete authenticate it redirect to the htmlnew.html page
app.js
var app = angular.module("appName", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'assests/index.html',
controller: 'loginCtrl'
})
});
app.controller('loginCtrl', function ($scope) {
var provider = new firebase.auth.GoogleAuthProvider();
$scope.googleSignin = function () {
firebase.auth()
.signInWithPopup(provider).then(function (result) {
var token = result.credential.accessToken;
var user = result.user;
console.log(token);
console.log(user);
firebase.auth().onAuthStateChanged(function user() {
if (user) {
window.location = 'htmlnew.html';
}
});
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
}
});
app.controller('SecondController', [function ($scope) {
$scope.googleSignout = function () {
firebase.auth().signOut()
.then(function () {
console.log('Signout Succesfull');
}, function (error) {
console.log('Signout Failed');
});
}
}]);
htmlnew.html
<html data-ng-app="appName">
<body ng-controller="SecondController">
<div id="message">
<h1>Welcome</h1>
<button ng-click="googleSignout()">Google Signout</button>
</div>
</body>
Here is the problem
1.) It throws the Uncaught Error: [$injector:modulerr] error while entering into htmlnew.html page.
2.) Signout is not working

You forgot to include fireBase module name in app declaration.
angular.module('appName', ['ngRoute','firebase'])
Refer https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-angularjs-and-firebase--cms-22391

You missed to inject Firebase as a dependency of your application. In your module definition, add firebase:
var app = angular.module("appName", ["ngRoute", "firebase"]);
Here is a JSFiddle demo using Firebase

Related

How to use one module for multiple controllers

How to use one module for multiple controllers, when these controllers are in different js files.
I have 3 js file
1. app.js
2. Login. js
3. Register.js
app.js
var app = angular.module("myApp", ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'Login/login.html',
controller: 'myCtrl'
})
.when('/register', {
templateUrl: 'Register/register.html',
controller: 'registerCntrl'
})
})
Login.js
var app = angular.module("myApp");
app.controller("myCtrl", function ($scope) {
$scope.login = function (data) {
console.log(data);
if (data.name == 'pinku' && data.pswd == '1234') {
console.log("Login Successfull");
} else {
console.log("Not successful");
}
};
$scope.moreInfo = function () {
alert("M in more info");
}
});
Register.js
var app = angular.module("myApp");
app.controller("registerCntrl", function ($scope) {
});
I have defined mymodule in my app.js file now i want to register my controller to that module and controllers are in different class. I have injected ng-Route in app.js. In login m using already defined module but m getting error
'Failed to instantiate module ngRoute due to:'
Thanks in advance
You can rather do:
angular.module("myApp")
.controller(...)
for both the controllers, rather than writing the variable here
Note: app.js should be loaded before any of the controllers for this to work.
This is one of the ways it can be done:
<html ng-app="myApp">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="controller1.js"></script>
<script type="text/javascript" src="controller2.js"></script>
</body>
</html>
Apart from this you can also use some task runners like gulp OR grunt to do that automatically.
If you load your app.js first, in other files you can inject your modules like
app = angular.module("myApp");
Note that I omit [] from the function call. It means that you are trying to get already defined module.

Error while trying to transfer an object using a view model

I am trying to display the username "bacon" whenever the user clicks on the button "home" using a vm(view model) in order to transfer the object user which contains the property userName but I get the following error.
app.js:1 Uncaught SyntaxError: Unexpected token <
index.controller.js:1 Uncaught SyntaxError: Unexpected token <
The project has the following hierarchy:
Here is my index.html located at the parent folder ./app
<!DOCTYPE html>
<html>
<head>
<title>MEAN Stack User Registration and Login Example Application</title>
</head>
<body class="container">
<!-- header -->
<header>
<ul class="nav nav-tabs">
<li ng-class="{active: activeTab === 'home'}"><a ui-sref="home">Home</a></li>
</ul>
<div class="flash-message" ng-if="flash">
<div class="{{'alert alert-' + flash.type}}" ng-bind="flash.message"></div>
</div>
</header>
<!-- main -->
<main ui-view></main>
<!-- footer -->
<footer></footer>
<!-- external scripts -->
<!-- application scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="app.js"></script>
<script src="home/index.controller.js"></script>
<!--<script src="app-services/user.service.js"></script>
<script src="app-services/flash.service.js"></script>-->
<!-- <script src="account/index.controller.js"></script>-->
</body>
</html>
Here is my app.js located at the parent folder ./app
(function () {
'use strict';
angular
.module('app', ['ui.router'])
.config(config)
.run(run);
function config($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home/index.html',
controller: 'Home.IndexController',
controllerAs: 'vm',
data: { activeTab: 'home' }
})
}
function run($http, $rootScope, $window) {
// add JWT token as default auth header
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;
// update active tab on state change
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
$rootScope.activeTab = toState.data.activeTab;
});
}
// manually bootstrap angular after the JWT token is retrieved from the server
$(function () {
// get JWT token from server
$.get('/app/token', function (token) {
window.jwtToken = token;
angular.bootstrap(document, ['app']);
});
});
})();
Here is my index.html located at the folder ./app/home
<h1>Hi {{vm.user.firstName}}!!</h1>
Here is my index.controller.js located at the folder ./app/home
(function () {
'use strict';
angular
.module('app')
.controller('Home.IndexController', Controller);
function Controller() {
var vm = this;
vm.user = null;
initController();
function initController() {
var user;
user.firstName = "bacon";
vm.user = user;
// get current user
//UserService.GetCurrent().then(function (user) {
// vm.user = user;
//});
}
}
})();

Angular: 'modulerr', "Failed to instantiate module

I'm trying to learn Angular and hitting a brick wall trying to add routes to my application.
I keep getting presented this error
'modulerr', "Failed to instantiate module
From other stackoverflow questions i gather its not from loading ngRoute correctly but angular-route.js is loaded in the head, and ngRoute is declared in my module construct so i'm a bit confused
My index file is as followed
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js"></script>
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js"></script>
<script src="js/app.js"></script>
<script src="js/animations.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="pgpChatApp">
<div class="view-container">
<div ng-view="" class="view-frame"></div>
</div>
</body>
</html>
My app file
'use strict';
var pgpChatApp = angular.module('pgpChatApp', [
'ngRoute',
'firebase',
'pgpChatAnimations',
'pgpChatControllers',
'pgpChatFilters',
'pgpChatServices'
]);
pgpChatApp.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/home", {
// the rest is the same for ui-router and ngRoute...
controller: "userAuth",
templateUrl: "partials/home.html"
}).when("/account", {
// the rest is the same for ui-router and ngRoute...
controller: "AccountCtrl",
templateUrl: "partials/msg_room.html",
resolve: {
// controller will not be loaded until $requireAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["Auth", function (Auth) {
// $requireAuth returns a promise so the resolve waits for it to complete
// If the promise is rejected, it will throw a $stateChangeError (see above)
return Auth.$requireAuth();
}]
}
});
}]);
My controller file
var pgpChatAppControllers = angular.module('pgpChatAppControllers', []);
pgpChatAppControllers.controller("userAuth", ["$scope", "$routeParams", "Auth",
function ($scope, $routeParams, Auth) {
$scope.createUser = function () {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
}).then(function (userData) {
$scope.message = "User created with uid: " + userData.uid;
}).catch(function (error) {
$scope.error = error;
});
};
$scope.removeUser = function () {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function () {
$scope.message = "User removed";
}).catch(function (error) {
$scope.error = error;
});
};
}]);
Has anyone got an idea what the fix is?
Thanks in advanced
[EDIT]
Full exception message
http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=pgpChatAnimations&p1=Error: [$injector:nomod] http://errors.angularjs.org/1.3.15/$injector/nomod?p0=pgpChatAnimations
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:6:417
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:21:412
at a (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:21:53)
at w.bootstrap (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:21:296)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:35:116
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:7:302)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:34:399)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:35:63
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:7:302)"
The url for angular-route is not working. Try using:
http://code.angularjs.org/1.2.0-rc.3/angular-route.js
I guess i my module names still weren't matching the defined modules in app.js
This diff shows the fix
https://github.com/jkirkby91/angular-firebase-chat/commit/35be74592197d16435adb322f0e24963108ed97a

My Basic Angular App failing me when i'm designing my First Mean stack UI

app.js
var myApp = angular.module('myApp',[]);
myApp.controller('mainCtrl',function($scope){
$scope.name="vignesh";
});
I'm doing a basic app building with MEAN Stack, for most of the parts we use Node API's to connect with MongoDB and user authentication,I'm done with my authentication part in Node.js but while designing routing UI I'm facing this issue
HTML
<!DOCTYPE>
<html ng-app="myApp">
<head>
<title>User Story</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-route.js"></script>
</head>
<body>
<div ng-controller="mainCtrl">{{name}}</div>
<script type="text/javascript" src="/service/authService.js"></script>
<script type="text/javascript" src="/controllers/controllers.js"></script>
<script type="text/javascript" src="/app.js"></script>
</body>
</html>
angular.module('authService',[])
.factory('Auth',function($http,$q,AuthToken){
var authFactory={};
authFactory.login=function(username,password){
return $http.post('/app/login',{
username:username,
password:password
}). sucess(function(data){
AuthToken.setToken(data.token);
return data;
})
}
authFactory.logout=function(){
AuthToken.setToken();
}
authFactory.isLoggedin=function(){
if(AuthToken.getToken())
return true;
else
return false;
}
authFactory.getUser=function(){
if(AuthToken.getToken())
return $http.get('/api/me');
else
return $q.reject({message:"user has no token set"});
}
return authFactory;
})
. factory('AuthToken', function($window){
var authTokenFactory={};
authTokenFactory.getToken=function(){
return $window.localStorage.getItem('token');
}
authTokenFactory.setToken=function(token){
if(token)
$window.localStorage.setItem('token',token);
else
$window.localStorage.removeeItem('token');
}
return authTokenFactory;
})
.factory('AuthInterceptor',function($q,$location,AuthToken){
var interceptorFactory={};
interceptorFactory.request=function(config){
var token=AuthToken.getToken();
if(token){
config.header['x-access-token']=token;
}
return config;
};
interceptorFactory.responseError=function(response){
if(response.status==403)
$location.path('/login');
return $q.reject(response);
}
})
controllers.js
angular.module('mainCtrl', [])
.controller('MainController', function($rootScope,$location,Auth){
var vm = this;
vm.loggedIn = Auth.isLogged();
$rootScope.$on('$routechangeStart',function () {
vm.loggedIn=Auth.isLogged();
Auth.getUser().then(function(data){
vm.user=data.data;
});
});
vm.doLogin= function(){
vm.processing=true;
vm.error='';
Auth.login(vm.loginData.username, vm.loginData.password)
.sucess(function (data) {
// body...
vm.user=data.data;
});
if(data.success)
$location.path('/');
else
vm.erroe=data.message;
}
vm.doLogout=function(){
Auth.logout();
$location.path('/logout');
}
})
error says:
Uncaught SyntaxError: Unexpected token
Uncaught Error: [$injector:modulerr] Failed to instantiate module
myApp due to: Error: [$injector:nomod] Module 'myApp' 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.
You need to initialize you app module correctly.
var myApp = angular.module('myApp', []);
Working Plunkr
Update
As you have different module per each JS file, you need to combine them while using any provider/service that module, As in your case you have used Auth service but the authService module has not injected.
Controllers.js
angular.module('mainCtrl', ['authService']) //injected authService module
.controller('MainController', function($rootScope,$location,Auth){
App.js
var myApp = angular.module('myApp',['mainCtrl']);
myApp.controller('mainCtrl',function($scope){

How to redirect to a URL after logging in with Firebase using AngularFire and AngularJS?

Upon the User logging in, I'd like the webpage to redirect. I've attempted two different ways to accomplish this:
Add a line right after '$scope.auth.$authWithOAuthPopup('google',AuthHandler)()' that redirects the url
Add an AuthHandler that redirect to a different page upon being logged in if successful
Although, the login works, the redirect doesn't work for an unknown reason.
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.0.2/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body ng-controller="ctrl">
<p>Welcome, {{user.google.displayName}}</p>
<button class="btn btn-lg btn-danger" id="Gbtn" ng-click="GoogleLogin()">
<i class="fa fa-google-plus-square fa-2x"></i>
Login with Google</button>
</body>
</html>
Javascript
<script>
function AuthHandler(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
window.location.href = "explore.html";
}
}
var app = angular.module("app", ["firebase"]);
app.service("Ref", ["https://crowdfluttr.firebaseio.com/", Firebase]);
app.factory("Auth", ["$firebaseAuth", "Ref", function($firebaseAuth, Ref) {
return $firebaseAuth(Ref);
}]);
app.controller("ctrl", ["$scope","Auth", function($scope,Auth) {
$scope.auth = Auth;
$scope.GoogleLogin = function () {
$scope.auth.$authWithOAuthPopup('google',AuthHandler)()
window.location.href = "explore.html";
};
}]);
app.run(["$rootScope", "Auth", function($rootScope, Auth) {
$rootScope.user = Auth.$getAuth();
}]);
Also, see here for my codepen: http://codepen.io/chriscruz/pen/YPGeYx?editors=101
You have to manually redirect in this case. Using $state.go('state where to go')
And states can be defined using $stateProvider.
Check the below 2 tutorials for basics of $stateProvider
http://learn.ionicframework.com/formulas/navigation-and-routing-part-1/
http://learn.ionicframework.com/formulas/navigation-and-routing-part-2/

Categories