How to get the data as a promise while saving? - angularjs

I getting the data from ng-model from html->controllers->services->Factories
After saving i got response is like this
This my response
Resource {_id: "56fe5ddc414e823023576508", productcode: "101", productname:"desktops",
__v: 0, isDeleted: false…}
$promise:undefined
$resolved:true
__v:0
_id:"56fe5ddc414e823023576508"
isDeleted:false
productcode:"101"
productitems:Array[1]
productname:"desktops"
__proto__:Object
myFacory code:
factmodule.factory("DashboardItemFactory",function($resource){
var ProductItemnew=[];
ProductItemInfoResourec=$resource("http://192.168.0.194:9070/productitems/:id",
{"id": "#id","productid":"#productid"}, {update: {method: "PUT"}});
return{
addProductItemnew:function(itemslist){
var items = new ProductItemInfoResourec(itemslist);
items.$save({"id":itemslist.productid},function(respdata){
console.log(respdata)
ProductItemnew.push(respdata);
console.log("Data Saved...")
},function(respdata){
console.log("Error while saving the data");
});
},
}
})
Please help me how make the data as promise..

You need to return promise object from the factory method. Resources have $promise property which is what you need. So it could be something like this:
factmodule.factory("DashboardItemFactory", function($resource) {
var ProductItemnew = [];
ProductItemInfoResourec = $resource("http://192.168.0.194:9070/productitems/:id", {
"id": "#id",
"productid": "#productid"
}, {
update: {
method: "PUT"
}
});
return {
addProductItemnew: function(itemslist) {
var items = new ProductItemInfoResourec(itemslist);
return items.$save({ id: itemslist.productid }).$promise.then(function(respdata) {
ProductItemnew.push(respdata);
console.log("Data Saved...", respdata)
return respdata; // or return ProductItemnew;
}, function(respdata) {
console.log("Error while saving the data");
throw new Error("Error while saving the data")
});
}
}
})
Just decide what you want this promise to resolve with: either original response from save request or maybe ProductItemnew array.

it is working for me with $q
factmodule.factory("DashboardItemFactory",function($resource,$q){
var ProductItemnew=[];
ProductItemInfoResourec=$resource("http://192.168.0.194:9070/productitems/:id/:itemid",
{"id": "#id","productid":"#productid"}, {update: {method: "PUT"}});
return{
addProductItemnew:function(itemslist){
var dfr = $q.defer();
var items = new ProductItemInfoResourec(itemslist);
items.$save({"id":itemslist.productid},function(respdata){
console.log(respdata)
ProductItemnew.push(respdata);
dfr.resolve(ProductItemnew);
console.log("Data Saved...")
return dfr.promise;
},function(respdata){
console.log("Error while saving the data");
});
}
}
})

Related

Fetching particular json key from controller AngularJS 1

Hi I am new in AngularJS and trying to fetch and show json key data separately to console window. I can able to fetch entire json data , but unable to fetch datas within a particular node. Where am I going wrong ?
Service.js
app.service("AppService", function($http) {
return {
network: [],
getAllService: function(network){
return $http({
method: 'GET',
url: 'http://99.126.4.6:3200/app/json/allDatas',
headers: {'Content-Type': 'application/json'}
})
.then(function(data) {
return data;
})
}
}
});
Controller :-
app.controller('getController', ['$scope','$http','AppService','$localStorage', function ($scope,$http,AppService,$localStorage) {
$scope.load = AppService.getAllService();
$scope.load.then(function(data) {
$scope.getAllData = data;
$scope.getId = data.ID;
$scope.getName = data.Name;
$scope.getDescription = data.Description;
console.log($scope.getId + $scope.getName + $scope.getDescription);
})
}]);
When I console getAllData I can see entire json response.But unable to fetch inner keys.
JSON response:-
Data
Array(1)
0
:
{$id: "1", ID: 1, Name: "APP", Description: "Something", Segments: Array(3)}
You are mixing the old syntax with a new one: .success vs. .then
.then() returns an Http Promise which wraps your response in an object. To pull out your data, you need to access .data first.
Fix this line from:
.then(function(data) {
return data;
})
to
.then(function(data) {
return data.data;
})
data is an array, so access it's value by index
$scope.load = AppService.getAllService();
$scope.load.then(function(data) {
angular.forEach(data, function(value) {
console.log(value.ID+" "+value.name++" "+value.escription);
});
})

Respone.say not working in Promise for Alexa Skill

i´m working on an Alexa Skill with nodejs.
When I want to get a response i don´t get any message when trying to get it with response.say(value). But when trying with console.log(value) i get the right response.
alexaApp.intent("Plot", {
"slots": { "Titel": "String"},
"utterances": ["Wovon handelt {Titel}"]
},
function(request, response) {
var titel = request.slot("Titel");
geturl(titel,1).then((speech) => {
console.log(speech); //right string
response.say(speech); //nothing
});
});
Any ideas how to get it working? I´m working with promises cause of the async of node to get my requests in time.
you should use synchronous call to get request. here a woking example :
var http = require('bluebird').promisifyAll(require('request'), { multiArgs: true });
app.intent('search', {
"utterances": [
"search ",
]
},
function(request, response) {
return http.getAsync({ url: url, json: true}).spread(function(statusCodesError, result) {
console.log(result)
});
})
You do need to use an async call, and return the promise.
var http = require('bluebird').promisifyAll(require('request')
alexaApp.intent("Plot", {
"slots": { "Titel": "String"},
"utterances": ["Wovon handelt {Titel}"]
},
function(request, response) {
var titel = request.slot("Titel");
return http.getAsync(titel,1)
.then((speech) => {
return response.say(speech);
}).catch(function(err){
return response.say(err);
});

Store new values into JSON

I have a $http.post that gives me a JSON
$http.post(url, {headers: {'Content-Type': 'application/json'} })
.success(function (data) {
myService.initialize(data);
})
The service in which I store the JSON looks like this:
app.service('myService', function() {
var json = "";
this.initialize = function(data) {
json = data;
};
});
This is the JSON I get:
{
"values": {
"id": "ABC_123",
"infotypes": [
{
"infotype": "AA1234",
"syften": [
{
"syfteId": 0
}
]
},
{
"infotype": "BB4567",
"syften": [
{
"syfteId": 0
}
]
}
]
}
}
Now, my problem is that I want to add a new infotype "CC6789" with syfteId "0" into the JSON.
I know how to access the different parts in the JSON, to display them in tables using ng-repeat and so on. But I don't have a clue how to add something into it.
If you wanna just do it in-memory, you can add a method to your service that can add some kind of infotype object:
app.service('myService', function() {
var json = "";
this.initialize = function(data) {
json = data;
};
this.addInfoType = function(infoType) {
if(json !== '') {
json.infotypes.push(infoType);
} else {
throw new Error('no json');
}
}
});
// somewhere else
myService.addInfoType({
"infotype": "CC6789",
"syften": [
{
"syfteId": 0
}
]
});
Keep in mind, this doesn't do any validation to the data structure you're passing into the service, so you might want to add that.

Node.js + Angular.js promises sync issue

I am working on a chat app which is Node.js + MongoDB (Mongoose library) on the server side, and Angular.js on the client side.
I have a database collection (MongoDB) for rooms (all the rooms in the app), which looks like this:
// ------- creating active_rooms model -------
var active_rooms_schema = mongoose.Schema({
room_name: String,
users: [String]
});
var active_rooms = mongoose.model('active_rooms', active_rooms_schema);
This database contains a room with all its users (i.e. "my cool room" with users: "mike", "joe", and "dave").
What I want to do is - every time a user wants to be in a chat room (with some room name) in my Angular.js client, I want to:
Create the room if it is not exists
Push that user into the users array of the room.
I know that because of 1, I will always have a room with an array of users.
This is my Angular relevant code: (I cannot give here the whole app because it is way too large and not relevant.)
$scope.enterRoom = function(info) {
$q.when(create_room_if_not_exists($scope.room)).then(add_user_to_room($scope.name, $scope.room));
$location.path("chat");
}
var create_room_if_not_exists = function(room_name) {
var deferred = $q.defer();
is_room_already_exists({
'name': room_name
}).then(function(response) {
if (!response.data.is_room_exists) {
register_room({
'name': room_name
});
console.log("room: " + room_name + ", was created");
deferred.resolve();
}
}, function(error) {
deferred.reject(error.data);
});
return deferred.promise;
}
var add_user_to_room = function(user_name, room_name) {
console.log(user_name)
add_user_to_room_request({
'user_name': user_name,
'room_name': room_name
});
}
var is_room_already_exists = function(info) {
return $http({
url: '/is_room_already_exists',
method: 'POST',
data: info
});
}
var add_user_to_room_request = function(info) {
$http({
url: '/add_user_to_room',
method: 'POST',
data: info
});
}
var register_room = function(info) {
return $http({
url: '/register_room',
method: 'POST',
data: info
});
}
What happens is that the 2nd action happens before the 1st one. When I print a log into the console, I see that, and I don't know why.
Both of these actions arrive through an HTTP request to the server - so I don't think the problem is there.
I am talking about the XHRs not chaining
A common cause of problems with chaining is failure to return promises to the chain:
var add_user_to_room = function(user_name, room_name) {
console.log(user_name)
//add_user_to_room_request({
return add_user_to_room_request({
//^^^^^^ ----- be sure to return returned promise
'user_name': user_name,
'room_name': room_name
});
}
If chaining is done properly, $q.defer is not necessary:
var create_room_if_not_exists = function(room_name) {
//var deferred = $q.defer();
//is_room_already_exists({
return is_room_already_exists({
//^^^^^^ --- be sure to return derived promise
'name': room_name
}).then(function(response) {
if (!response.data.is_room_exists) {
console.log("room: " + room_name + ", to be created");
//register_room({
return register_room({
//^^^^^^ ----- return promise to further chain
'name': room_name
});
//deferred.resolve();
} else {
return room_name;
//^^^^^^ ----- return to chain data
};
}, function(error) {
//deferred.reject(error.data);
throw error;
//^^^^^ ------- throw to chain rejection
});
//return deferred.promise;
}
If a promise is returned properly, $q.when is not necessary:
$scope.enterRoom = function(info) {
//$q.when(create_room_if_not_exists($scope.room))
// .then(add_user_to_room($scope.name, $scope.room));
return create_room_if_not_exists($scope.room)
.then(function() {
return add_user_to_room($scope.name, $scope.room));
}).then(function()
$location.path("chat")
});
}
The rule of thumb with functional programming is -- always return something.
Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.
-- AngularJS $q Service API Reference - Chaining Promises.
Try this:
$scope.enterRoom = function (info) {
return create_room_if_not_exists($scope.room)).then(function(){
return add_user_to_room_request({ 'user_name': $scope.name, 'room_name': $scope.name });
}).then(function(){
$location.path('chat');
});
}
var create_room_if_not_exists = function (room_name) {
var deferred = $q.defer();
return is_room_already_exists({ 'name': room_name }).then(function (response) {
if (!response.data.is_room_exists) {
console.log("room: " + room_name + ", is being created");
return register_room({ 'name': room_name });
}
return response;
})
}
var is_room_already_exists = function (info) {
return $http({
url: '/is_room_already_exists',
method: 'POST',
data: info
});
}
var add_user_to_room_request = function (info) {
return $http({
url: '/add_user_to_room',
method: 'POST',
data: info
});
}
var register_room = function (info) {
return $http({
url: '/register_room',
method: 'POST',
data: info
});
}

How to get JSON out of Angular $resource

How do i get the get JSON data out of a $resource?
Currently all return values out of User.query and User.$save() are factory objects. I would like to be able to keep $scope.users as raw JSON so I can modify it and post the data to another URL.
myApp.factory("User", function($resource) {
return $resource("/api/users/:Id", { Id: "#Id"}, {
"update": {method:"PUT"},
"query": { method:"GET", isArray: true }
});
});
var users = User.query(function() {
$scope.users = users;
});
You can transform the response like this:
myApp.factory("User", function($resource, $http) {
return $resource("/api/users/:Id", { Id: "#Id"}, {
"update": {method:"PUT"},
"query": {
method:"GET",
isArray: true,
transformResponse: [function (data, headersGetter) {
return [{ result: JSON.parse(data) }];
}].concat($http.defaults.transformResponse)
}
});
});

Resources