Angular LocalStorage Service - javascript

i have passed a lot of time to get data from controller to another using Angularjs
i found this module https://github.com/grevory/angular-local-storage and i like it , i get object object issue [object Object]
my first controller code
$scope.getUserFunction = function () {
$scope.username;
$scope.password;
$scope.data;
//var data = {username: 'akram',password: "yes"};
$http({
method : 'POST',
url : 'http://localhost:8080/JersyBackEnd/resources/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
//headers: {username: "toto",password:"toto"},
})
.then(function(data) {
// $window.location.href = "/about.html";
// $cookieStore.put('user',data);
localStorageService.set('users',JSON.stringify(data));
// console.log("Employee",x);
$scope.data = data;
console.log(data);
}, function (error) {
console.log(error)
});
};
and second controller code
$scope.getEmployee = function () {
//var cookie = $cookieStore.get('user');
//console.log("Employee"+cookie);
var users = JSON.parse(localStorageService.get('users'));
console.log("happiens"+users);
}
i get happiens[object Object] in console
1 . how to resolve this problem ?
2 . is this a good idea to get data from controller to another
and thanks :)

console.log("happiness", users);
Or
console.log("happiness", JSON.stringify(users));
OR
console.log("happiness" + JSON.stringify(users));
One of them will work.

Related

AngularJS w/ Flask backend, representing the data passed from backend

I am working on an Single page app using angular with a python / flask back-end that links to mongodb.
The issue that I am having is that, once the data is passed from the back-end using a $http get request from angular as an object which I cannot seem to get to display in the front-end. I am able to display it in the console but I am puzzled as to why it will not display in the front end.
When I use a declared array of JSON objects in the factory the information passes through fine but, when using the data taken from the back-end it does not display.
I am also able to curl request the data required.
Thank you in advance for any help :)
.controller('topicCtrl', function(posts, $scope){
"use strict";
var p = this;
p.posts = posts.getPosts();
})
.factory('posts', function(data){
"use strict";
var posts={};
posts.item = data.response;
/*
- Add post function below -
post title & body to be entered
by the user.
The posts here will need to be passed down to a lower
layer, with aim of sending JSON Object w/ post request to
api.
*/
posts.getPosts = function(){
posts.item = data.getData();
};
posts.addPost = function(title, body){
data.postData(posts.item.push({title: title, body: body}));
};
return posts;
});
.factory('data', function($http, $log){
"use strict";
var data = {};
/*data.item = [{id: 1, title:"An Intro to A!", body:"Hello there AAA! :) "},
{id: 2, title:"An Intro to B!", body:"Hello there BBB! :)"},
{id: 3, title:"An Intro to C!", body:"Hello there! ccc:)"}
];*/
data.getData = function(){
var i = 0;
$http({
method: 'GET',
url: '/h',
type: 'application/json'
}).then(function success(response){
$log.info("1 get", response);
data = response.data;
$log.info(data.response);
}, function error(response){
$log.info(" damn"+response);
});
};
data.postData = function(data){
$http({
method: 'POST',
url: '/h'
}).then(function sucess(response){
$log.info(" hello from post"+response);
data.item = JSON.stringify(data.item);
}, function error(response){
$log.info(" damn from post "+response);
});
};
return data;
});
<div class="card card-block">
<l class="list" ng-repeat="post in list.posts">
</br>
<h4 class="card-title">{{post.title}}</h4>
<p class="card-text">{{post.body}}</p>
<!--- the functionality of the below will be added towards end, time permitting-->
Like
Comment
</br
</l>
</div>
</div>
some additional info that might be helpful:
image of the console
I've made some changes to the code below. Some variation of this will work.
.controller('topicCtrl', function(posts, $scope){
$scope.posts = [];
$scope.getPosts = function() {
posts.getPosts().then(function(response){
//success
console.log("Success Get");
console.log(response);
$scope.posts = response;
}, function(error){
//error
console.log("error");
});
};
})
.factory('posts', function(data){
"use strict";
var posts={};
posts.getPosts = function(){
return data.getData();
};
return posts;
});
.factory('data', function($http, $log){
"use strict";
var data = {};
data.getData = function(){
$http({
method: 'GET',
url: 'http://127.0.0.1:5000/h',
type: 'application/json'
});
};
return data;
});
for anyone who may need it in the future! :)
I added a for loop that iterates over the response data and stores each element into an array then returned the array.
data.getData = function(){
var i;
var myObj = [];
$http({
method: 'GET',
url: '/h'
}).then(function success(response){
$log.info(" hello the get", response.data);
for (i = 0; i < response.data.length; i++){
myObj[i] = (response.data[i]);
}
if(response.data.length === 0){
$log.info("empty set");
}else{
//data.item = response.data;
$log.info("SUCCESS!!" + myObj);
}
}, function error(response){
$log.info(" damn"+response);
});
return myObj;
};
.factory('posts', function(data, $log){
"use strict";
var posts={};
posts.item = data.getData();
posts.addPost = function(title, body){
data.postData(posts.item.push({title: title, body: body}));
};
$log.info("in the posts" + posts.item);
return posts;
});
.controller('topicCtrl', function(posts){
"use strict";
var p = this;
p.posts = posts.item;
})

AngularJS : Getting Error on adding $scope in factory-service

studentService.js
app.factory('saveStudentService',['$http','$scope',function ($http,$scope) {
var studentData = {};
studentData.save = function(jsondata){
var action = "student";
var method = "POST";
$http({
url: action,
method: method,
headers: {'Content-Type': 'application/json'},
data: jsondata
}).success(function(data, status, headers, config) {
toastr.success(status +' : Data has been submitted successfully ');
}).error(function(data, status, headers, config) {
toastr.error(status + ' : Data has not been submitted successfully ');
});
};
return studentData;
}]);
I am getting this error
angular.js:13642Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20saveStudentService
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:6:412
If from studentService.js, $scope is being removed, i.e
app.factory('saveStudentService',['$http',function ($http) {
this code is working properly, and not getting any error message in console.
Following is the studentController.js file from where this studentService is being called.
StudentController.js
app.controller('saveStudentCtrl',['$scope', 'saveStudentService', function($scope,saveStudentService) {
$scope.submit_create_student = function() {
var jsondata = $scope.student;
saveStudentService.save(jsondata);
}
}]);
but if same thing i.e $scope is being added in the updateStudentService then this code is working as expected.
app.controller('updateStudentCtrl',['$scope','retriveStudentService', 'updateStudentService', function($scope,retriveStudentService, updateStudentService) {
$scope.getStudentDataFromServer = function() {
retriveStudentService.get();
};
$scope.submit_update_student = function(e) {
updateStudentService.update();
}
}]);
Could someone please clarify, what is happening here. Though able to use same thing in one place, but not able to use same process at someother place.
You cannot inject scope into services. You can inject it to controllers.

AngularJS - Posting data to API is not working

I am trying to send data that a user puts into a textarea and text input to and API that will save the data.
Here is the function:
$scope.forward = function() {
$http({
url: 'http://appsdev.pccportal.com:8080/ecar/api/reject/' + carID,
method: "POST",
data: "comments=" + this.comments,
data: "recipient=" + this.recipient,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
then(function(response) {
$scope.output = response.data;
})
}
What it does when it is run is it logs only the recipient and not the comments. I am guessing because I am using "data" twice and it is only recognizing the last one (in this case "recipient"). How can I pass 2 values through this to the API.
Thanks
As you said, you're overwriting the data key from the plain object you're passing to $http, send it all together:
data: { recipient: this.recipient, comments: this.comments }
pass it as an object:
data : {comments: this.comments, recipient: this recipient}
This got it working just fine:
data: 'recipient='+encodeURIComponent(this.recipient)+'&comments='+encodeURIComponent(this.comments),

How to pass form parameters to Rest using angularjs services?

I try to pass my form parameters to java rest backend but i cant.
controller
$scope.addNewThing = function () {
Myservice.addNew($scope.name);
};
service
addNew: function (name) {
var Foo = $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {}}
});
var results = Foo.save({name: name}, function(data) {
results = data;
});
return results;
}
//also tried this version of code
addNew: function(name) {
return $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {name: 'test'}}
});
}
rest backend function
#POST
#Produces("application/json")
#Path("/addNew")
public Response addNew(#FormParam("name") String name) {
try {
//when i check name here it is always null
...
}
}
I can't pass the html form parameter to java rest backend via angular. Also tried to change #FormParam to #QueryParam but it didn't work.
Did you set the default content-type on $http POST requests?
app.config(function($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
I don'n know how to receive params value in java but I can show how to pass params from angular service. when you will want to pass params then you should use :paramsName in your URL path.
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {name: '#name'}, {
'post': {method: 'GET'}
});
return addNewItem.post({name: name});
}
or if you don't use /:name in your url you should pass in your header
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {}, {
'post': {method: 'GET', headers: { 'name': name }}
});
return addNewItem.post({name: name});
}
NB: your Content-Type should be application/json
You can try this:
CONTROLLER
$scope.addNewThing = function () {
yourService.addNew($scope.name);
};
SERVICE
angular.module('MyApp')
.service('yourService',['$http', function ($http) {
this.addNew = function (data) {
$http({
url: 'YourURL',
method: 'POST',
data: data, // your $scope.name
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function (response) {
console.log('good');
})
.error(function (response) {
console.log('error');
});
};
}]);
JAVA REST API
#POST
#Path("/addNew")
#Consumes("*/*")
public Response addNew(String name) {
// use here your String name
}
Using jQuery params solved my problem
Here is the correct way:
Myservice.addNew().save($.param({
name:$scope.name
}),function(data){
console.log(data);
},function(err){
console.log(err);
});
I can pass the parameters like this with $resource service.

how to use query with parameters in angularJS?

I need to use a query method in Angular JS service connecting to a restful web service with the url /users/userId/sensors/. The restful web service works fine when I enter the url in the browser but when I want to get the result in Angular service when calling the find method I get nothing.
controller.js:
appControllers.controller('sensorController',
function ($scope, Scopes, SensorService) {
var userId = Scopes.get('id');
$scope.sensors = [];
$scope.sensors = function () {
SensorService.find(userId, function (data) {
$scope.sensors = data;
});
};
});
service.js:
appServices.factory('SensorService', function ($resource) {
var url = '/iots-web/rest/users/:userId/sensors/:path';
return $resource(url, {path: '#path', userId: '#userId'}, {
query: {method: 'GET',isArray: true},
find: {method: 'GET', params: {userId: '#userId'}, isArray: true},
create: {method: 'POST'},
update: {method: 'PUT', params: {id: '#id'}},
delete: {method: 'DELETE', params: {id: '#id'}}
});
});
Scopes is another service I use to share the usrId between controllers and it works fine so there is no problem with getting the userId.
Correct way to pass userId into resource call would be:
SensorService.find({userId: userId}, function(data) {
$scope.sensors = data;
});
Also to avoid confusion, it's better to rename sensors function to something else:
$scope.sensors = [];
$scope.getSensors = function() {
SensorService.find({userId: userId}, function(data) {
$scope.sensors = data;
});
};
the problem looks as you are trying to access a javascript variable in an anonymous function
$scope.sensors = function () {
SensorService.find(userId, function (data) {
$scope.sensors = data;
});
userId does not exist in this anonymous function.
$scope.sensors = [];
$scope.sensors = function () {
SensorService.find(userId, function (data) {
$scope.sensors = data;
});
};
This seems suspicious to me. You first assign an empty Array to $scope.sensors, then override this value with a function, and then override it again with data, when it arrives.
Try fixing this first and then check if your problem still persists.

Categories