$scope var not updating on Parse update - angularjs

I am building an app using ionic and parse. I am updating a boolean in parse based on a click. Everything works on parse end, I see the user object updated in the console after the function runs, however the scope variable is not updating until user logs out, comes back to the page, and then usually has to even refresh again just to see the $scope.isInstagramLinked updated to its true value.
Controller
var app = angular.module('myApp.controllers.account', []);
app.controller('AccountCtrl', function ($scope, $state, $cordovaOauth, AuthService) {
$scope.isInstagramLinked = AuthService.user.attributes.is_instagram_linked;
$scope.linkInstagram = function() {
$cordovaOauth.instagram('######', [], {})
.then(function(result) {
console.log("Response Object -> " + JSON.stringify(result));
console.log(result.access_token);
// save the access token & get user info
AuthService.setInstagramAccessToken(result.access_token).then(function() {
console.log('Token saved!');
});
}, function(error) {
console.log("Error -> " + error);
});
}
$scope.unlinkInstagram = function() {
AuthService.removeInstagramInfo().then(function() {
console.log('Insta unlinked');
console.log(AuthService.user.attributes);
});
}
});
Service
var app = angular.module('myApp.services.authentication', []);
app.service('AuthService', function ($q, $http, $ionicPopup) {
var self = {
user: Parse.User.current(),
'setInstagramAccessToken': function(token) {
var d = $q.defer();
var user = self.user;
user.set("instagram_access_token", token);
user.save(null, {
success: function(user) {
self.user = Parse.User.current();
d.resolve(self.user);
},
error: function(user, error) {
$ionicPopup.alert({
title: "Save Error",
subTitle: error.message
});
d.reject(error);
}
});
self.setInstagramUserInfo(token);
return d.promise;
},
'setInstagramUserInfo': function(token) {
var d = $q.defer();
var endpoint = 'https://api.instagram.com/v1/users/self?access_token=' + token + '&callback=JSON_CALLBACK';
$http.jsonp(endpoint).then(function(response) {
console.log(response.data.data.username);
console.log(response.data.data.id);
var user = self.user;
user.set('is_instagram_linked', true);
user.set('instagram_username', response.data.data.username);
user.set('instagram_user_id', response.data.data.id);
user.save(null, {
success: function(user) {
self.user = Parse.User.current();
d.resolve(self.user);
},
error: function(user, error) {
$ionicPopup.alert({
title: "Save Error",
subTitle: error.message
});
d.reject(error);
}
});
});
},
'removeInstagramInfo': function() {
var d = $q.defer();
var user = self.user;
user.set('is_instagram_linked', false);
user.set('instagram_access_token', null);
user.set('instagram_username', null);
user.set('instagram_user_id', null);
user.save(null, {
success: function(user) {
self.user = Parse.User.current();
d.resolve(self.user);
},
error: function(user, error) {
$ionicPopup.alert({
title: "Save Error",
subTitle: error.message
});
d.reject(error);
}
});
return d.promise;
}
};
return self;
});
I tried something like this at the end of the function but get an error saying Error: [$rootScope:inprog] $digest already in progress
$scope.$apply(function () {
$scope.isInstagramLinked = false;
});

I'm guessing that you're assuming that the following line
$scope.isInstagramLinked = AuthService.user.attributes.is_instagram_linked;
is going to make '$scope.isInstagramLinked' update anytime 'AuthService.user.attributes.is_instagram_linked' updates. That's not the case, though. Because 'AuthService.user.attributes.is_instagram_linked' references a primitive (boolean) value, it just assigns it - it doesn't maintain any kind of reference to it - that only happens with objects.
You need to manually set $scope.isInstangramLinked = true in the $cordovaOauth.instagram() success/"then" handler.
tl;dr:
$scope.isLinked = false;
someFunction().then(function(){
$scope.isLinked = true; // this is what you're missing
})
.error(function(err){...})
If you don't want to set it manually, you can also use $scope.$watch to watch 'AuthService.user.attributes.is_instagram_linked' for changes, and then update '$scope.isInstagramLinked' when it does.

Related

Get 404 Not Found with PUT request in MEAN app

I have an Edit button on my event-detail page that goes to a new page where user can update the current selected event. I have no trouble using GET to get single/all events and POST to create new event. But I'm stuck on updating existing event and constantly get 404 error: PUT http://localhost:3000/api/events 404 (Not Found)
On my server route I have:
//return event-details
app.get('/api/events/:id', events.getEventById);
//update event
app.put('/api/events/:id', events.updateCurrentEvent);
Server side event controller:
exports.updateCurrentEvent = function(req, res) {
Event.findById(req.params.id, req.body, function(err, event) {
var event = req.body;
if(!event) {
res.statusCode = 404;
res.send({ error: 'Not found'});
}
event.title = req.body.title;
event.desc = req.body.desc;
event.date = req.body.date;
event.duration = req.body.duration;
event.address = req.body.address;
event.city = req.body.city;
event.state = req.body.state;
event.save(function (err) {
if (!err) {
log.info("event updated");
res.send({ status: 'OK', event:event });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
log.error('Internal error(%d): %s',res.statusCode,err.message);
}
});
});
My $resource service:
app.factory('mvEvent', function($resource) {
var EventResource = $resource('/api/events/:_id', {_id: "#id"}, {
update: {method:'PUT', isArray:false}
});
return EventResource;
});
my client-side controller:
angular.module('app').controller('mvUpdateEventCtrl', function($scope, $routeParams, $location, mvEvent) {
$scope.event = mvEvent.get({_id:$routeParams.id})
.$promise
.then(function(event) {
$scope.event = event;
console.log($scope.event);
$scope.title =$scope.event.title;
$scope.desc = $scope.event.desc;
$scope.date = $scope.event.date;
$scope.duration = $scope.event.duration;
$scope.address = $scope.event.address;
$scope.city = $scope.event.city;
$scope.state = $scope.event.state;
});
$scope.updateEvent = function() {
$scope.event.$update(function() {
}, function(error) {
$scope.error = error.data.message;
});
}
});
My client side routes:
var app = angular.module('app', ['ngResource', 'ngRoute', 'ui.bootstrap']);
app.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
//events route
.when('/events', {
templateUrl: '/partials/events/event-list',
controller: 'mvEventListCtrl'
})
//events detail route
.when('/events/:id', {
templateUrl: '/partials/events/event-details',
controller: 'mvEventDetailsCtrl'
})
//update event route
.when('/events/:id/update', {
templateUrl: '/partials/admin/event-update',
controller: 'mvUpdateEventCtrl'
})
});
Getting the event details showing in the each text field is as far as I can get. As soon as I hit 'Update event' Button I get 404 error and it seems to lie somewhere in my server side code. I've seen quite a bit of different approaches implementing PUT request, with or without routeParams, using findById then save or findByIdAndUpdate. I'm wondering if there is a standard way to do this. Thanks in advance!!
Remove the line var event = req.body; from your server side controller. Firstly, it is not required. Secondly, it is same as the name of the document returned by Event.findById callback, and that's getting overridden by the variable declaration.
exports.updateCurrentEvent = function(req, res) {
Event.findById(req.params.id, req.body, function(err, event) {
var event = req.body; // <<==== Remove this line
if(!event) {
res.statusCode = 404;
res.send({ error: 'Not found'});
}
event.title = req.body.title;
event.desc = req.body.desc;
event.date = req.body.date;
event.duration = req.body.duration;
event.address = req.body.address;
event.city = req.body.city;
event.state = req.body.state;
event.save(function (err) {
if (!err) {
log.info("event updated");
res.send({ status: 'OK', event:event });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
log.error('Internal error(%d): %s',res.statusCode,err.message);
}
});
});
}

Ionic logout not clearing http service data

when I click logout button, its changing the state, but not refreshing the page, because of this, my login page text boxes still having entered data. and If i loggIn with new data, Property details http request not pulling the new data.
I tried, $location.path , $state.go but no use,
can any one help me please.
Login controller
.controller('LoginCtrl', function($scope, $rootScope, AuthenticationService,ClientDetails, $ionicPopup, $state) {
$scope.data = { clientId: '', lastName: '', email: ''};
$scope.login = function () {
AuthenticationService.Login($scope.data.clientId, $scope.data.lastName, $scope.data.email, function(response) {
if(response.success) {
ClientDetails.setDetails(response.data);
$state.go('app.home');
console.log(response);
} else {
$scope.error = response.message;
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: $scope.error
});
}
});
};
})
getting properties through service:
.factory('PropertyDetails',
['$http', '$rootScope',
function ( $http, $rootScope) {
var clientId = $rootScope.globals.clientDetails.ClientId;
var service = {};
service.getProperties = function(callback){
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
var data = ''; var status = ''; var message = '';
var response = {};
var Request = $http({
method: 'GET',
url: 'http://example.com/'+clientId,
data: data
})
Request.success(function(jdata, headers) {
if( headers === 200 ){
if(typeof jdata == 'object'){
status = jdata.Status;
message = jdata.Message;
data = jdata.Data;
$rootScope.globals.properties = data;
}else{
status = false;
message = "Response data is not a object!";
}
}else{
status = false;
message = "Something went wrong!";
}
//response = { success : status, message : message, data: data };
response = { success : status, message : message, data: $rootScope.globals.properties };
callback(response);
//callback($rootScope.globals.properties);
})
Request.error(function(data, headers){
if(typeof data == 'object'){
message = data.Message;
}else{
message = "Client not found.";
}
response = { success : false, message : message };
callback(response);
});
};
service.clearDetails = function(){
$rootScope.globals.properties = {};
};
return service;
}])
My logout controller:
.controller('menuCtrl', function($scope, $rootScope, ClientDetails, PropertyDetails,$timeout,$ionicHistory, $state,$location){
$scope.logOut = function(){
ClientDetails.clearDetails();
PropertyDetails.clearDetails();
$timeout(function () {
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
$ionicHistory.nextViewOptions({ disableBack: true, historyRoot: true });
$state.go('login');
}, 30);
}
})
Thank you
Many Way to clear textbox first of controller call one time to load in ionic if you want to reload again data you used
$scope.$on('$ionicView.enter', function() {
//here some code
});
above code when you open page this code is running every time[load controller].
its simple way.

Making promises in modules

I try to make facebook registration module in my app. Facebook API is faster than my Angular controller, so promise should be used here. The problem is that $q seems to be an empty object and defer function is undefined.
module:
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'herecomesmycode');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$q', '$ionicPlatform', '$state', 'authService', 'datacontext', '$location'];
function FacebookAPI(UserService, $q, $ionicLoading, fbAppId, $state, authService, datacontext, $location) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
};
and here $q.defer is undefined:
function fbRegister() {
console.log($q.defer);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
Without using promise, it gets fast from API but all variables I want to fill with values from API, are initiated before API finishes and are undefined.
The whole module:
(function() {
'use strict';
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'myappkey');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$ionicPlatform', '$state', 'authService', '$q'];
function FacebookAPI(UserService, $ionicLoading, fbAppId, $state, authService, $q) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
}
function fbRegister() {
console.log($q);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
function getApiData() {
var formData = {};
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email,birthday", ["public_profile", "email", "user_birthday"],
function (result) {
if (result.gender == "male") {
result.gender = '1';
} else {
result.gender = '2';
}
formData = {
name: result.first_name + " " + result.last_name,
email: result.email,
birthday: new Date(result.birthday),
gender: result.gender
}
console.log("moduĊ‚" + formData);//here we have nice and neat data
return formData;
}, function(res) {
});
}
};
//This is the success callback from the login method
function fbLoginSuccess(response) {
var fbLogged = $q.defer();
if (!response.authResponse) {
fbLoginError("Cannot find the authResponse");
return;
}
var expDate = new Date(
new Date().getTime() + response.authResponse.expiresIn * 1000
).toISOString();
var authData = {
id: String(response.authResponse.userID),
access_token: response.authResponse.accessToken,
expiration_date: expDate
}
authService.facebookLogin(response.authResponse.accessToken).then(function() {
fbLogged.resolve(authData);
});
};
//This is the fail callback from the login method
function fbLoginError(error) {
var fbLogged = $q.defer();
fbLogged.reject(error);
alert(error);
$ionicLoading.hide();
};
//this method is to get the user profile info from the facebook api
function getFacebookProfileInfo() {
var info = $q.defer();
facebookConnectPlugin.api('/me', "",
function(response) {
info.resolve(response);
},
function(response) {
info.reject(response);
}
);
return info.promise;
}
//This method is executed when the user press the "Login with facebook" button
function fbLogin() {
if (!cordova) {
//this is for browser only
facebookConnectPlugin.browserInit(fbAppId);
}
//check if we have user's data stored
var user = UserService.getUser();
facebookConnectPlugin.getLoginStatus(function(success) {
//alert(JSON.stringify(success, null, 3));
if (success.status === 'connected') {
// the user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email", ["public_profile", "email"],
function(result) {
//alert("Result: " + JSON.stringify(result));
//alert(result.first_name);
})
var accessToken = success.authResponse.accessToken;
authService.facebookLogin(accessToken).then(function() {
$state.go('app.map');
}, function(err) { alert('auth failed: ' + JSON.stringify(err, null, 2)); });
} else {
//if (success.status === 'not_authorized') the user is logged in to Facebook, but has not authenticated your app
//else The person is not logged into Facebook, so we're not sure if they are logged into this app or not.
$ionicLoading.show({
template: 'Loging in...'
});
// permissions from facebook
facebookConnectPlugin.login([
'email',
'public_profile',
'user_about_me',
'user_likes',
'user_location',
'read_stream',
'user_photos'
], fbLoginSuccess, fbLoginError);
fbLogged.promise.then(function(authData) {
var fb_uid = authData.id,
fb_access_token = authData.access_token;
//get user info from FB
getFacebookProfileInfo().then(function(data) {
var user = data;
user.picture = "http://graph.facebook.com/" + fb_uid + "/picture?type=large";
user.access_token = fb_access_token;
//save the user data
//store it on local storage but it should be save it on a database
UserService.setUser(user);
$ionicLoading.hide();
$state.go('app.map');
});
});
}
});
}
})();

Resolving a promise in a dependent AngularJS service

I have a simple AngularJS app running in a Chrome Extension making use of the Storage API. Having an issue with the async nature of Storage; I've abstracted the storage away into a 'UserService' that sets and gets the data as a factory:
app.factory('UserService',
function($q, AppSettings) {
var defaults = {
api: {
token: AppSettings.environments[1].api.token
},
email: ''
};
var service = {
user: {},
save: function() {
chrome.storage.sync.set({'user': angular.toJson(service.user)});
},
restore: function() {
var deferred = $q.defer();
chrome.storage.sync.get('user', function(data) {
if(!data) {
chrome.storage.sync.set({'user': defaults});
service.user = defaults;
} else {
service.user = angular.fromJson(data.user);
}
deferred.resolve(service);
});
return deferred.promise;
}
};
// set the defaults
service.restore().then(function(data) {
console.log(data);
return data;
});
});
The console.log() call above dumps out the data as expected. However, when I am including the UserService in other factories (I have an APIService that makes use of a user-specific API token), the UserService parameter is being flagged as 'undefined' in the code below:
app.factory('APIService',
function($resource, $http, UserService, AppSettings) {
var token = UserService.user.api.token;
...
});
I am sure I am not fully grasping the Angular promise pattern in terms of consuming resolved promises throughout the app.
Updated code:
app.factory('UserService',
function($q, AppSettings) {
var defaults = {
api: {
token: AppSettings.environments[1].api.token
},
email: ''
};
var service = {
user: {},
save: function() {
chrome.storage.sync.set({'user': angular.toJson(service.user)});
},
restore: function() {
var deferred = $q.defer();
chrome.storage.sync.get('user', function(data) {
if(!data) {
chrome.storage.sync.set({'user': defaults});
service.user = defaults;
} else {
service.user = angular.fromJson(data.user);
}
deferred.resolve(service.user);
});
return deferred.promise;
}
};
// set the defaults
service.restore().then(function(data) {
console.log(data);
return data;
});
return service;
});
Edit/Additional Info:
Ok, getting close. Have refactored so that I am returning the object properly, but the issue now is that when the APIService gets created and tries to use the properties of the UserService object, they simply don't exist yet as they are only created after the async restore method is resolved. So it's not possible to access the UserService.user.api.token property, as it doesn't exist at that point, so the question is, how do I get that data in APIService when I need it if it is not available at that point? I'm trying to avoid having to put the entire contents of APIService into a callback that fires after a hypothetical new UserService.get() method that calls the callback on resolution of the promise. Any final guidance appreciated.
Your service is wrong. Please look at my fix:
app.factory('UserService',
function($q, AppSettings) {
var defaults = {
api: {
token: AppSettings.environments[1].api.token
},
email: ''
};
var service = {
user: {},
save: function() {
chrome.storage.sync.set({'user': angular.toJson(service.user)});
},
restore: function() {
var deferred = $q.defer();
chrome.storage.sync.get('user', function(data) {
if(!data) {
chrome.storage.sync.set({'user': defaults});
service.user = defaults;
} else {
service.user = angular.fromJson(data.user);
}
deferred.resolve(service.user); // <--- return the user in here
});
return deferred.promise;
}
};
// set the defaults
service.restore().then(function(data) {
console.log(data);
return data;
});
return service; // <--- return the service to be used injected when injected
});
[EDIT]
answer to your new question: Dont access user directly. create a new function in your service like getUser() that returns a promise. In that function return the user if it is already retreived otherwise return the restore() function:
var service = {
user: null,
getUser: function() {
if (service.user)
{
var deferred = $q.defer();
deferred.resolve(service.user);
return deferred.promise;
}
else
return service.restore();
},
save: function() {
chrome.storage.sync.set({'user': angular.toJson(service.user)});
},
restore: function() {
var deferred = $q.defer();
chrome.storage.sync.get('user', function(data) {
if(!data) {
chrome.storage.sync.set({'user': defaults});
service.user = defaults;
} else {
service.user = angular.fromJson(data.user);
}
deferred.resolve(service.user); // <--- return the user in here
});
return deferred.promise;
}
};
You're not returning an object from your factory. So when you try to inject your UserService parameter, it gives undefined because you haven't returned anything from your UserService function.
If you return your service variable, I think you'll get the behavior you're looking for.

Deferred promise not deferring

Hi in the following Angular controller i try to initiate facebook login with Parse.com.
So I created a promise triggered on fbLogIn. What it is supposed to do, is first login to facebook, and grab first_name and store it in fieldValuesService.ff.
THEN, it is supposed to access this value and do something with it. For illustration purpose I just used console logs.
What happens is that the second console.log in second then is triggered before the first one from first .then thus is undefined.
I don't understand why anything in the second .then can be triggered before first one in this situation.
Also second problem, after a logout, the fbLogIn function is sometime inactive: it won't trigger the login process again.
If you have a clue on this issue your help will be greatly appreciated.
.controller('logController',
function ($scope, $q, fieldValuesService) {
var defer = $q.defer();
defer.promise
.then(function() {
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
alert("User signed up and logged in through Facebook!");
} else {
$scope.currentUser = user;
$scope.$apply();
FB.api('/me', function(response) {
fieldValuesService.ff = response.first_name;
console.log(fieldValuesService.ff); //logs bob
});
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
})
.then(function(){
console.log(fieldValuesService.ff); //logs undefined
});
$scope.fbLogIn = function() {
defer.resolve();
};
// Parse log out
$scope.logOut = function(form) {
Parse.User.logOut();
$scope.currentUser = null;
};
});
Maybe if you restructure your code, things will become a little bit easier.
I recommend to refactor everything FB related into its own service like:
module.factory('FBService', function ($q) {
var login,
logout,
getInformation;
login = function () {
var defered = $q.defer();
Parse.FacebookUtils.logIn(null, {
success: function (user) {
defered.resolve(user);
},
error: function (user, error) {
defered.reject(user, error);
}
});
return defered.promise;
};
logout = function () {
var defered = $q.defer();
Parse.User.logOut();
defered.resolve();
return defered.promise;
};
getInformation = function () {
var defered = $q.defer();
FB.api('/me', function (response) {
defered.resolve(response);
});
return defered.promise;
}
return {
login: login,
logout: logout,
getInformation: getInformation
};
});
module.controller("LoginCtrl", function ($scope, FBService, fieldValuesService) {
$scope.fbLogIn = function () {
FBService.login().then(function (user) {
$scope.currentUser = user;
return FBService.getInformation();
}).then(function (information) {
fieldValuesService.ff = information.first_name;
console.log(fieldValuesService.ff);
});
};
$scope.logOut = function () {
FBService.logout().then(function () {
$scope.currentUser = null;
});
};
});

Resources