Why does angular 1.5 routes break controllers? - angularjs

angular.module('CalendarTest')
.config(function($routeProvider){
$routeProvider.when('/signup', {
templateUrl: '/signup.html'
})
$routeProvider.when('/login', {
templateUrl: '/login.html'
})
$routeProvider.when('/testPage', {
templateUrl: '/testPage.html'
})
$routeProvider.when('/visitform', {
templateUrl: '/visitform.html'
})
});
The router loads when index loads with out an error.
angular.module('formLoginApp', ['ngCookies'])
.controller('formLoginController', ['$scope', '$cookies', ($scope, $cookies) => {
$scope.email = '';
$scope.password = '';
$scope.update = (user) => {
const req = new XMLHttpRequest();
req.open('POST', 'http://localhost:4002/login', true);
req.onload = (serverResponse) => {
if (req.readyState === 4) {
if (req.status === 200) {
$cookies.put("user", req.response);
} else {
console.log('no response');
}
} else {
console.log('no response');
}
};
req.setRequestHeader("Authorization", "Negotiate");
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(JSON.stringify(user));
};
}]);
when I try to access this page login.html, i get formLoginController is not a (and nothing here...). I am not sure why this is going on. I tried simplifying the issue and adding a controller from the docs but that also breaks. How can I fix this?

Related

AngularJS $routeProvider Resolve Method Not Working

In my code, I define the following two routes:
$routeProvider.when('/problem/report', {
templateUrl: '/app/management/problem/reportAProblem.html',
controller: 'reportAProblemCtrl',
resolve: {
authorized: function($http, $location) {
var path = $location.path();
return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
var data = response.data;
if (response.data.result === 'NOT_AUTHORIZED') {
throw "NOT_AUTHORIZED";
}
return data;
})
}
}
});
$routeProvider.when('/problem', {
templateUrl: '/app/management/problem/problem.tmpl.html',
controller: 'problemCtrl',
resolve: {
authorized: ['$authorization', function($authorization) {
$authorization.authorize();
}]
}
});
The first case seems to work. However, the second case has had the function refactored into a Service, and AngularJS does not seem to be waiting for the Promise to resolve before displaying the page.
The refactored code looks like the following:
angular.module('authorization', [])
.factory('$authorization', ['$http', '$location',function($http, $location) {
var $authorization = {};
$authorization.authorize = function() {
var path = $location.path();
return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
var data = response.data;
if (response.data.result === 'NOT_AUTHORIZED') {
throw "NOT_AUTHORIZED";
}
return data;
});
}
return $authorization;
}]);
Can anyone tell me why the second case above doesn't wait for the promise to resolve before displaying the page?
Add return:
authorized: ['$authorization', function($authorization) { **return** $authorization.authorize(); }]

AngularJS Template URL Loads Before Authorization Resolves [duplicate]

In my code, I define the following two routes:
$routeProvider.when('/problem/report', {
templateUrl: '/app/management/problem/reportAProblem.html',
controller: 'reportAProblemCtrl',
resolve: {
authorized: function($http, $location) {
var path = $location.path();
return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
var data = response.data;
if (response.data.result === 'NOT_AUTHORIZED') {
throw "NOT_AUTHORIZED";
}
return data;
})
}
}
});
$routeProvider.when('/problem', {
templateUrl: '/app/management/problem/problem.tmpl.html',
controller: 'problemCtrl',
resolve: {
authorized: ['$authorization', function($authorization) {
$authorization.authorize();
}]
}
});
The first case seems to work. However, the second case has had the function refactored into a Service, and AngularJS does not seem to be waiting for the Promise to resolve before displaying the page.
The refactored code looks like the following:
angular.module('authorization', [])
.factory('$authorization', ['$http', '$location',function($http, $location) {
var $authorization = {};
$authorization.authorize = function() {
var path = $location.path();
return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
var data = response.data;
if (response.data.result === 'NOT_AUTHORIZED') {
throw "NOT_AUTHORIZED";
}
return data;
});
}
return $authorization;
}]);
Can anyone tell me why the second case above doesn't wait for the promise to resolve before displaying the page?
Add return:
authorized: ['$authorization', function($authorization) { **return** $authorization.authorize(); }]

UI router login form submission

I currently have code for a form submission login that works with ng-route, however i want to convert it to UI router. I currently have MVC java controller for rest services. However here is my main app with configure statements:
var reportingDashboard = angular
.module('reportingDashboard', [ 'ngRoute', 'ui.router', 'ngMdIcons', 'chart.js'])
.config(
function($routeProvider, $httpProvider, $stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
/* $routeProvider.when('/', {
templateUrl : '/home/temp.html',
controller : 'home',
controllerAs : 'controller'
}).when('/login', {
templateUrl : '/home/loginCtrl/login.html',
controller : 'navigation',
controllerAs : 'controller'
}).otherwise("/")
*/
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login',{
url:'/login',
templateUrl : '/home/loginCtrl/login.html',
controller : 'navigation',
controllerAs : 'controller'
})
.state('home',{
url:'/',
templateUrl : '/home/temp.html',
controller : 'home',
controllerAs : 'controller'
})
.state('home.index', {
views:{
'': {
templateUrl:"/home/reportingTemp/repoHtml.html"
},
'reportingGraph':{
templateUrl:'/home/reportingTemp/repoGraph.html',
controller: 'reportingGraphCtrl'
}
}
})
.state('home.admin', {
views:{
'': {
templateUrl:"/home/adminTemp/adminHtml.html"
},
'adminGraph':{
templateUrl:'/home/adminTemp/adminReport.html',
controller:'adminCtrl'
}
}
})
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).run(function(auth) {
// Initialize auth module with the home page and login/logout path
// respectively
console.log("is the auth function being called?")
auth.init('/', '/login', '/logout');
});
From this I have the auth factory:
reportingDashboard.factory(
'auth',
function($rootScope, $http, $location) {
enter = function() {
if ($location.path() != auth.loginPath) {
console.log($location.path());
auth.path = $location.path();
if (!auth.authenticated) {
$location.path(auth.loginPath);
}
}
}
var auth = {
authenticated : false,
loginPath : '/login',
logoutPath : '/logout',
homePath : '/',
path : $location.path(),
authenticate : function(credentials, callback) {
var headers = credentials && credentials.username ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
auth.authenticated = true;
} else {
auth.authenticated = false;
console.log("The use isnt logged in")
}
callback && callback(auth.authenticated);
$location.path(auth.path==auth.loginPath ? auth.homePath : auth.path);
}).error(function() {
auth.authenticated = false;
callback && callback(false);
});
},
clear : function() {
$location.path(auth.loginPath);
auth.authenticated = false;
$http.post(auth.logoutPath, {}).success(function() {
console.log("Logout succeeded");
}).error(function(data) {
console.log("Logout failed");
});
},
init : function(homePath, loginPath, logoutPath) {
auth.homePath = homePath;
auth.loginPath = loginPath;
auth.logoutPath = logoutPath;
auth.authenticate({}, function(authenticated) {
if (authenticated) {
$location.path(auth.path);
}
})
// Guard route changes and switch to login page if unauthenticated
$rootScope.$on('$routeChangeStart', function() {
enter();
});
}
};
return auth;
});
From this I have the navigation controller:
reportingDashboard.controller(
'navigation',
function($route, auth, $location) {
var self = this;
self.credentials = {};
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
self.authenticated = function() {
return auth.authenticated;
}
self.login = function() {
auth.authenticate(self.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
self.error = false;
} else {
console.log("Login failed")
self.error = true;
}
})
};
self.logout = auth.clear;
});
Also i have the home controller as well:
reportingDashboard.controller('home', function($http) {
var self = this;
$http.get('/user/').success(function(data) {
self.user = data.name;
});
});
the console just returns a 401 and redirects me to the home page of the application. Any advice would be great Thankyou!! I can include any more info if it helps.
My suggestion: in angular.run function bind listener to $stateChangeStart event. Each time user will go to some state, you will check that user is authenficated. If he is, continue transition, else - save transition state and params, go to login page and after user will successfully logged in, you will redirect him to requested state/page. Something like this:
myApp.run(function ($rootScope, principal, $state, myStateProvider, userService) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (toState.name !== 'login') {
myStateProvider.setNextState(toState, toParams);
}
if (!principal.isAuthenticated()) {
event.preventDefault();
principal.checkAuthentication().then(function() {
$state.go(toState, toParams);
});
} else if (principal.isAuthenticated() && toState.name === 'login') {
event.preventDefault();
myStateProvider.redirectFromLogin();
}
});
})

Facebook SDK not loaded during the call to get login status

I am using Facebook SDK to build an application however I am faced with a challenge, I try to get the login status of the user before I redirect him to his profile page, however during the call to get the login status I get the error that
ReferenceError: FB is not defined
now the SDK is being loaded asynchronously so the error makes sense, how can i resolve the problem. Here is my code:
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "Views/ListPages.html",
controller: 'MainCtrl',
resolve: {
authentication:["$location", "LoginFactory", function($location, LoginFactory){
console.log("in resolve");
LoginFactory.getLoginStatus()
.then(function(response){
if(response){
$location.path('/login');
}
else{
$location.path('/');
}
});
}]
}
})
.when('/login', {
templateUrl: "Views/Login.html",
controller: 'LoginCtrl'
})
.otherwise
({redirectTo: '/'});
});
loginApp.factory("LoginFactory", function ($rootScope, $q, $location, UserInfo) {
return {
getLoginStatus: function () {
var deferred = $q.defer();
FB.getLoginStatus(function (response) {
if(!response || response.error){
deferred.reject(new error("User Not logged in."));
}
else{
deferred.resolve(response);
}
});
return deferred.promise;
},
login: function () {
FB.login(function (response) {
if (response.authResponse === "connected") {
$rootScope.$broadcast('fb_connected', {facebook_id:response.authResponse.userID});
} else {
$rootScope.$broadcast('fb_login_failed');
}
}, {scope: "read_insights, publish_pages, manage_pages"});
},
logout: function () {
FB.logout(function (response) {
if (response) {
$rootScope.$broadcast('fb_logout_succeded');
$location.path('/login');
} else {
$rootScope.$broadcast('fb_logout_failed');
}
});
}
};
angular.module("LoginCtrlModule", ["FacebookLogin"])
.controller("LoginCtrl", ["$scope", "$location", "LoginFactory", function ($scope, $location, LoginFactory) {
$scope.login = function () {
LoginFactory.login();
$scope.on("fb_connected", function () {
$location.path("/");
});
$scope.on("fb_login_failed", function(){
$location.path("/login");
});
}
}]);
app.run(function ($rootScope, $location, LoginFactory) {
window.fbAsyncInit = function () {
FB.init({
appId: '',
status: true,
cookie: true,
xfbml: true
});
};
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
});
I was following these posts:
AngularJS- Login and Authentication in each route and controller
http://www.sitepoint.com/implementing-authentication-angular-applications/
But the problem i am facing is different.
Thanks for the help.
I think the solution is to not call the FB.getLoginStatus() but rather have an object that contains the User information and the access token, each time I try to route I should check if the User info object is null, in case if its not null then call the check login status method and accordingly take the route or not to take the route.

MEAN stack pass parameter within router

I'm a newbie to MEAN stack development. Trying to follow this tutorial https://thinkster.io/mean-stack-tutorial/ to get a simple web app working. I posted my code in the following. I created a middle layer parameter called post (see router.js file) to get a particular post. In my postCtrl, I want to pass the post/postId to the factory and get the particular post.
//$scope.post = postFactory.getById(id);
According to the tutorial, the post should be detected automatically from URL route. So I wonder how should I utilize it to get the post I want? Thanks for your time in advance
AngularController.js
var app = angular.module("littleStar" , ["service", "ui.router"]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: "/home.html",
controller: 'mainCtrl'
})
.state('post', {
url:'/post/{id}',
templateUrl: '/post.html',
controller:'postCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
app.controller("mainCtrl", ["$scope", "$http", "postFactory", function ($scope, $http, postFactory) {
postFactory.get().success(function(data){
$scope.posts = data;
});
$scope.addPost = function() {
var title = $scope.title;
var link = $scope.link;
if (!title || title === "" || !link || link === "") {
return;
}
var newPost = {
"title": title,
"link": link
}
postFactory.create(newPost)
.success(function (data) {
postFactory.get().success(function(allPosts){
$scope.posts = allPosts;
});
});
$scope.title = "";
$scope.link = "";
};
$scope.incrementPost = function(post){
post.upvotes += 1;
};
}]);
app.controller("postCtrl", ["$scope", '$stateParams', "postFactory", function($scope, $stateParams, postFactory){
//$scope.post = postFactory.get($stateParams.id);
//$scope.post = postFactory.getById($stateParams.id);
$scope.addComment = function(){
var currentComments = postFactory.post[$stateParams.id].comments;
currentComments.push({
author:$scope.author,
body: $scope.body,
upvotes: 0
});
$scope.body = "";
}
$scope.incrementComment = function(comment){
comment.upvotes += 1;
}
}]);
router.get('/posts/:post', function(req, res) {
res.json(req.post);
});
router.param('post', function(req, res, next, id) {
var query = Post.findById(id);
query.exec(function (err, post){
if (err) { return next(err); }
if (!post) { return next(new Error('can\'t find post')); }
console(id);
req.post = post;
return next();
});
});
angularService.js
var service = angular.module("service", []);
service.factory("postFactory", ["$http", function($http){
return {
get : function(){
return $http.get("/posts");
},
create: function(newPost){
return $http.post("/post", newPost);
},
delete : function(id){
return $http.delete("/post/" + id);
},
getById : function(id){
return $http.get("posts/" + id);
}
}
}]);
You should be able to make the get post route in the following way:
router.get('/posts/:post', function(req, res) {
var query = Post.findById(req.params.post);
query.exec(function (err, post){
res.json(post);
});
});

Resources