browser not saving data from localstorage when page refreshing - angularjs

I have a input field and when i input data, the localstorage set it perfectly, but when i refresh my page, the data is lost
$scope.member_save = function(){
console.log("new members:", $scope.person);
var json = JSON.stringify($scope.person)
localStorage.setItem('userData', json)
var data = JSON.parse(localStorage.getItem('userData'));
if (data) {
$scope.members.push(data);
}
$scope.person = {};
};

Related

Unable to access the object properties returned from firebase

This is probably a noob question as I couldn't find any similar questions here in stackoverflow. I am writing an ionic-angularjs application with firebase as the backend. I've a data snapshot returned by firebase snapshot.val() method and this is how the data shows up in my chrome console(attached pic)
var tmp = {};
CurrUser.getEventdesc(eventid).then(function (result) {
tmp = result;
console.log(tmp.Description);
});
CurrUser is a factory and getEventdesc is a function in the factory. The getEventdesc function looks like below:
getEventdesc: function(id) {
var deferred = $q.defer();
ref.child('Events').orderByChild('Eventid').equalTo(id).on('value', function (snapshot) {
event = snapshot.val();
console.log(event);
deferred.resolve(event);
});
return deferred.promise;
}
Now I'm trying to access the 'Description' property by tmp.Description in my angularjs controller but i get an 'undefined' error. I would be grateful if anyone could help me to access the object properties. Thanks for your time.
Update 2:
var tmp = {};
var newtemp = {};
CurrUser.getEventdesc(eventid).then(function (result) {
tmp = result;
for (var itemID in tmp) {
newtmp = tmp[itemID];
};
console.log(newtmp.Description);
});
Regards,
You're retuning the whole firebase object, not just the requested id, try this:
event = snapshot.val();
deferred.resolve(event[id]);

Angularjs $http cache refresh

I need to to refresh the cache after i add new data to database.
angular.module('app').factory('myService', function ($http,$cacheFactory) {
var profileCache=$cacheFactory('profiles');
//get list of items
function getItem(){
var request=$http({
method:'get',
url:domain+'/api/v1/items/list',
cache:profileCache,
params:{
action:'get'
}
});
return(request.then(response.data));
}
// Post items
function addItem(item){
var request=$http({
method:'post',
url:domain+'/api/v1/items/add',
data:item
});
return(request.then(response.data));
}
})
I want to refresh the cache once the item is added,so that the cache can have new changed data.
as you can read here
https://docs.angularjs.org/api/ng/service/$http
$http responses are not cached by default
but if you have particular environment and you need to prevent any caching you can add a date time to your request
example
function getItem(){
var d = new Date();
var n = d.getDate();
var request=$http({
method:'get',
url:domain+'/api/v1/items/list?' + n,
cache:true,
params:{
action:'get'
}
});
return(request.then(response.data));
}
var $httpDefaultCache = $cacheFactory.get('$http');

Promises - I get the same result after $q.all

I have this code:
return WordPress.getAllCategories()
.then(function (cats) {
var category = {};
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
To load latest articles from each category for a magazine main page (using WordPress REST api with $http requests). The process is as follow:
1. Load all categories.
2. Get latest post from each category.
3. Get the media of the latest post.
4. Build the category.post object based on the post data and add the thumbnail from the media received (post-specific).
5. After all promises are resolved, $scope.categories = categories to apply for view.
The problem:
With the code above, I can see the console logs search for different posts and medias properly, but at the end I get an array containing the categories, all posts are the same. Same title, content, thumbnail image and everything.
What am I doing wrong with the promises here?
P.S. All WordPresss service functions work properly. They return a resolved promise after receiving the necessary data via $http requests from the WordPress blog.
Regards.
Try this way:
return WordPress.getAllCategories()
.then(function (cats) {
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
var category = {}; // moved declaration here to return new instance each time
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
You were returning same category object instance, I just create new instance every time inside getMediaById callback

400 Bad request while sending restful request using angularJS

I am using angularJs and rest controllers for making web service call. I am getting 400 bad request. When I was making a request to change the status of the user then I am getting the error. Please find the below code for js file, controller and UI.
Js Controller-
var user=angular.module('userApp', ['ngAnimate']);
user.controller('userController',function($scope,$http){
var urlBase=window.location.pathname;
$scope.selection = [];
$scope.toggle=true;
$scope.statuses=['YES','NO'];
$scope.sortType= 'name'; // set the default sort type
$scope.sortReverse= false; // set the default sort order
$scope.searchUser= ''; // set the default search/filter term
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
//get all users and display initially
$http.get(urlBase+"/users")
.success(function(data){
$scope.users = data;
});
$scope.addUser = function addUser() {
if($scope.firstName=="" || $scope.lastName=="" || $scope.email == "" || $scope.mobile == ""|| $scope.status == ""){
alert("Insufficient Data! Please provide values for task name, description, priortiy and status");
}
else{
$http.post(urlBase + '/users/insert/' +$scope.firstName+'/'+$scope.lastName+'/'+$scope.email+'/'+$scope.mobile+'/'+$scope.status)
.success(function(data) {
$scope.users = data;
$scope.firstName="";
$scope.lastName="";
$scope.email="";
$scope.mobile="";
$scope.status="";
$scope.toggle='!toggle';
});
}
};
$scope.archiveUser = function archiveUser(id){
console.log(":: Value of id :"+id);
$http.post(urlBase+'users/archive/'+id)
.success(function(data) {
$scope.users = data;
console.log(":: Data updated and displayed.")
})
.failure(function(data){
alert("Failed to archieve task ::"+data);
});
};
});
A part in User interface where the code is being called , i am using ng-repeat for displaying values and then on click of button calling archiveUser(). Id value is coming fine.
<button class="btn" ng-Click='archiveUser(x.id)'><i class="fa fa-archive"></i></button>
Spring Controller for handling request-
#RequestMapping(value="users/archive/{userIds}",method = RequestMethod.POST,headers="Accept=application/json")
public List<User> archiveUser(#PathVariable int userId) {
User user = new User();
user=userService.getUserService(userId);
List<User> users=userService.getAllUserService();
return users;
}
The problem was with 's' as Paqman commented. I removed 's' and then save & tried, got the correct result that was expecting. Thanks Paqman.

Angularfire current logged in user's data

I am using Angularfire for my login system and trying to get current logged in user's username for purpose of using in controller. Firts getting uid from $getAuth and sync it with data in database. But what I am trying below is not working.
.factory("Auth", function($firebaseAuth) {
var ref = new Firebase("URL");
return $firebaseAuth(ref);
})
.factory("Konusma", function($firebaseObject) { //When you give user's uid to this factory its gives you user data in database.
return function(xm) {
var ref = new Firebase("URL");
var userdata = ref.child('users').child(xm);
return $firebaseObject(userdata);
}})
.controller("chatCtrl", function(Auth, Konusma) {
var userx = Auth.$getAuth(); //Current logged in user's uid and email
var chatci = function() { //Trying to get current logged in user's username and other data according to uid which is comes from Auth.$getAuth.
Konusma(userx.uid).$loaded().then(function(data){
return data.username;
});
};
As mentioned in comments -
You are trying to get the data before user is authenticated.
So in your controller , instead of :
var userx = Auth.$getAuth();
you can use this :
var userx = {};
Auth.$onAuth(function(authData) {
var userx = authData;
// or bind to scope -
// $scope.authData = authData;
});
this will also update your authData variable every time auth status is change.
Anyway - you still need to call: currentUser = chatci() only after user is loggedIn ,
and not evrey time that auth is change.
The best way is to use it with router, see here : https://www.firebase.com/docs/web/libraries/angular/guide/user-auth.html#section-routers
So the controller is loaded only after auth is success.
But for your example - you can add this to your controller:
Auth.$waitForAuth().then(function(authData){
if (authData){
currentUser = chatci()
}
});

Resources