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(); }]
Related
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(); }]
I have an app where my main state makes a resolve makes an http call and fetches an array.
Then, the child array is supposed to display one object from this array, but it seems that the variables from the controller are defined too early and don't get updated properly, so the child comes out empty.
I've tried it without http call (var array = [array]), and it works fine, but not with the http call.
Any tips on how to fix this?
Here's the controllers:
.controller('appCtrl',['$scope', 'SearchService','fair', function($scope, SearchService, fair){
$scope.data = SearchService;
$scope.datafairs = $scope.data.flatexhibitors;
console.log($scope.datafairs);
}])
.controller('ChildController',['$scope', 'exhibitor', '$filter', function($scope, exhibitor, $filter){
$scope.$watch(function() { return $scope.fair; }, function(newVal) {
$scope.fairs = newVal;
console.log($scope.fairs);
$scope.chosenexhibitor = $filter("filter")($scope.fairs, {'slug':exhibitor}, true);
}, true);
}])
The service:
.factory("SearchService", function($http) {
var service = {
flatexhibitors : [],
datafairs : [],
getAllExhibitors : function (wop) {
var searchindex = wop;
console.log(searchindex);
var url = '../register/backend/databaseconnect/getexhibitors.php';
var config = {
params: {
search: searchindex
},
cache:true
};
$http.get(url, config).then(function (data) {
service.datafairs = data.data.rows;
for (var i in service.datafairs) {
service.flatexhibitors.push(service.datafairs[i].doc);
};
return service.flatexhibitors;
});
}
}
return service;
})
And the states:
.config(function($stateProvider) {
$stateProvider.state('berliner', {
url: '/berlinerliste',
params : {search: 'Berliner 2017'},
resolve: {
fair: function(SearchService, $stateParams) {
return SearchService.getAllExhibitors($stateParams.search);
}
},
views: {
'header': {
templateUrl: 'header.htm'
},
'main':{
templateUrl: 'bl2017.htm',
controller: 'appCtrl'
}
}
})
.state('berliner.exhibitor', {
url: '/{id}',
resolve: {
exhibitor: function($stateParams) {
var slug = $stateParams.id;
return slug;
}
},
views: {
'header': {
templateUrl: 'header.htm'
},
'wop':{
templateUrl: 'exhibitor.htm',
controller: 'ChildController'
}
}
})
})
I've managed to replicate the issue in a Plunkr.
Change the getAllExhibitors to return a promise like below:
getAllExhibitors : function (wop) {
var searchindex = wop;
console.log(searchindex);
var url = '../register/backend/databaseconnect/getexhibitors.php';
var config = {
params: {
search: searchindex
},
cache:true
};
return $http.get(url, config).then(function (data) {
service.datafairs = data.data.rows;
for (var i in service.datafairs) {
service.flatexhibitors.push(service.datafairs[i].doc);
};
return service.flatexhibitors;
});
}
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?
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.
I'm new in angular/ui-route and firebase.
Do you know if it's possible to resolve firebase data using ui-route ?
I tryed the following states :
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: './assets/app/views/contacts/contacts.html',
resolve: {
contacts: ['contacts',
function( contacts){
return contacts.all();
}],
contactsFb: WHAT TO SET ???
},
controller: ['$scope', '$state', 'contacts', 'utils', 'contactsFb',
function ( $scope, $state, contacts, utils, contactsFb) {
// Working Fine but not from firebase
$scope.contacts = contacts;
// Can't make it works... :-(
$scope.contacts = contactsFb;
}]
})
Here is the factory:
.factory('contactsFb', function($firebase) {
var url='https://evet.firebaseio.com/contacts';
return $firebase(new Firebase(url));
})
.factory('contacts', ['$http', function ($http, utils) {
var path = './assets/app/models/contacts.json';
var contacts = $http.get(path).then(function (resp) {
return resp.data.contacts;
});
var factory = {};
factory.all = function () {
return contacts;
};
factory.get = function (id) {
return contacts.then(function(){
return utils.findById(contacts, id);
})
};
return factory;
}])
Can't make it works... :-(
Maybe you can help me ?
Many thanks!
Try something like this:
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: './assets/app/views/contacts/contacts.html',
resolve: {
loadContacts: function(contactsFb) {
return contactsFb.promiseToHaveContacts();
}
},
controller: function ($scope, contactsFb) {
$scope.contacts = contactsFb.contacts;
}
})
.factory('contactsFb', function($firebase, $q) {
return {
contacts: null,
promiseToHaveContacts: function() {
var deferred = $q.defer();
if (this.contacts === null) {
this.contacts = $firebase(new Firebase('https://evet.firebaseio.com/contacts'));
this.contacts.$on('loaded', function(loadedData) {
deferred.resolve();
});
}
else {
deferred.resolve();
}
return deferred.promise;
}
};
});