get and getList why no have the same unit? - angularjs

In my application I'm having the bellow problem
SERVER RESPONSE DATA
route /users
{ data: [
{ id: 5, name: 'peter' },
{ id: 10, name: 'adan' }
] }
route /users/5
{ data: { id: 5, name: 'peter' } }
case01
Restangular.one('users', 5).get().then(function(user){
$scope.user = user;
});
case02
Restangular.all('users').getList().then(function(users){
$scope.user = users[0];
});
In my case02 I can access $scope.user.id, but in case01 I have that to do $scope.user.data.id (what's not preferible when I render this in my template with {{ user.id }} where I have that use {{ user.data.id }} )
In my case02 I can change my data and use $scope.user.save(), but in my case01 I can't access this function
In my restangular I configure this for handle data from server when I use getList because it come in one object and not in one Array
RestangularProvider.setResponseInterceptor(function(response, operation, what) {
if (operation === "getList") {
// from:
// {data: [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]}
// to:
// [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]
return response.data;
}
return response;
});
So I would not work, because then I will have a normal JS object and not a Restangular object, the Restangular object has several methods that I still intend to use the same $scope, so we would like to preserve this.
example:
In an item from a case02 consultation (array) I have an object with methods of Restangular:
all (), allUrl (), one (), oneUrl (), ... and the properties of the object I sought (id, name) within $ scope.user.
{
all: function(){...},
allUrl: function(){...},
one: function(){...},
oneUrl: function(){...},
...
id: data_from_user,
name: data_from_user
}
In an item from a case01 query (object) I have an object with methods of Restangular within $ scope.user and object properties that sought (id, name) within $ scope.user.data.
{
all: function(){...},
allUrl: function(){...},
one: function(){...},
oneUrl: function(){...},
...
data: {
id: data_from_user,
name: data_from_user
}
}
For this reason it would not work the solution you presented because it is okay to work with restangular the subject, not an object of normal JS, but thank you for the answer Tim Castelijns.

if (operation === "getList") {
// from:
// {data: [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]}
// to:
// [{ id: 1, name: 'peter' }, { id: 2, name: 'adan' }]
return response.data;
}
return response;
If operation is getList, you return response.data, which is
[
{ id: 5, name: 'peter' },
{ id: 10, name: 'adan' }
]
but if operation is not getList, you return response, which is the entire object, including the data sub-object
{
data: {
id: 5,
name: 'peter'
}
}
Your choice to return different results depending on what operation it is, is the reason you need to do user.data.id for case01, because you assign the result to user with then(function(user), when in fact user represents the entire data sub-object containing the user.
You should be able to solve it by changing to this
Restangular.one('users', 5).get().then(function(response){
$scope.user = response['data'];
});

Related

Cannot read property 'map' of undefined in sequelize nodejs

This is my api:
exports.getService = function(req, res) {
var limit = 10; // number of records per page
var offset = 0;
Service.findAndCountAll({
raw: true,
where: {
shop: req.user.shop
}
}).then((data) => {
var page = req.params.page; // page number
var pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
Service.findAll({
// raw: true,
limit: limit,
offset: offset,
$sort: {
id: 1
},
where: {
shop: req.user.shop
},
include: [{
model: Categoryservice,
attributes: ['id'],
include: [{
model: Category,
attributes: ['id', 'name'],
}]
}],
}).then(function (services) {
var services=JSON.parse(JSON. stringify(services));
console.log('=====stringify==========>>',services);
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
}).catch(function(error) {
res.status(500).send('Internal Server Error');
});
};
I am using map in last then fuction ,
It contains a error map undefined in the server..
I want want a out like below given json using the map fuction.
Actually i need this out put:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [
1,
2
]
}
my JSON. stringify(services) out put is:
=====stringify==========>> [ { id: 2,
username: null,
name: null,
image: null,
service: 'mobile',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '20',
per: '10',
tax: '1',
activity: null,
createdAt: '2018-03-14T07:30:57.000Z',
updatedAt: '2018-03-14T07:30:57.000Z',
categoryservices: [ [Object], [Object] ] },
{ id: 1,
username: 'sam',
name: 'New Service',
image: '/images/uploads/22-Feb-2018/f96334384cd78754454c5e4e05e20fc0-dragon_pattern_red_black_9666_1920x1080.jpg',
service: 'battery',
shop: '$2a$10$NWpbmgtzQAxRZ1ugvdC7LOlorBU36xoGHm1L.k.KmFqDO/7oSmBLu',
min: '5',
per: '1',
tax: '1',
activity: '2018-03-14T06:01:36.000Z',
createdAt: '2018-03-14T06:01:36.000Z',
updatedAt: '2018-03-14T06:01:36.000Z',
categoryservices: [] } ]
I was beginner of using map function,
so,I am confused in map ,
so please give any solution to this problem.
You are stringifying your array that comes back. You can't do that if you plan to use .map on it. Remove that code and try again.
.then(function (services) {
var arr = services.categoryservices.map(item => item.category.id)
services.cats = arr;
delete services.categoryservices;
console.log('only for the testing========>',services);
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
});
I think we are missing something because the output you pasted doesn't have the category.id attribute that you are returning from the item passed in to map. Is that what you are trying to target? That's off topic, but this code may not work for what you are trying to achieve but will run the map though.
Looks like services is an array, based on the console.log. If you want the id's of all categories, you can do
let categoryIds = [];
categoryIds = services.reduce((categoryIds, service) => {
let ids = service.categoryservices.map(category => category.id);
for(let id of ids) {
if(categoryIds.indexOf(id) === -1) {
categoryIds.push(id)
}
}
return categoryIds;
}, categoryIds);
If you want to have category ids as cats in each service, you can do,
var services=JSON.parse(JSON. stringify(services));
services.forEach(service) => {
service.cats = service.categoryservices.map(category => category.id);
delete service.categoryservices;
});
res.status(200).json({
'result': services,
'count': data.count,
'pages': pages
});
Hope this helps!

Update Sequelize Array

I have looked everywhere, and I have not found an easy to understand method of updating a sequelize array, like this with a normal string:
db.User.update({name:req.body.name},{where : {username:req.body.username}}).then(function(user) {
res.json(user);
})
Sequelize doesn't support bulk updates using an array, see https://github.com/sequelize/sequelize/issues/4501
You have to implement a custom function.
Here is a basic example to give you an idea :
var promises = [];
userArray.forEach(function(user){
promises.push(db.User.update({name:user.name},{where : {username:user.username}});
});
Promise.all(promises).then(function(){
// success
}, function(err){
// error
});
Which I myself resolved as follows:
case 1: If you want to update multiple lines at the same value with different conditions
db.User.update({ name: 'name request' }, {
where: {
$or: [{ name: 'test 1', password: 'sasaccsa' }, {
name: "test 2"
}]
}
}).then(function(user) {
//query generate
// UPDATE `User` SET `name`='name request' WHERE ((`name` = 'test 1' AND `password` = 'sasaccsa') OR `name` = 'test 2')
res.json(user);
});
case 2: if you want to update multiple lines with different values for different types of reviews:
var arrayUpdate = [{
name: 'test 1',
id: 1
}, {
name: 'test 2',
id: 2
}, {
name: 'test 3',
id: 3
}];
sequelize.Promise.each(arrayUpdate, function(val, index) {
return db.User.update({
name: val.name
},{
where:{
id: val.id
}
}).then(function(user) {
}, function(err){
});
})
.then(function(updateAll){
//done update all
res.json(updateAll);
}, function(err){
});

Draw map based on selected city in selectbox in angularjs

i have a select box for city which has number of cities getting through ng-options. i need to show the map on the website based on city selected in the selectbox.
this is how i am getting city names
// Code goes here
$scope.data = [{
cities: [{
id: 1,
title: 'Mysore'
}, {
id: 2,
title: 'Bangalore'
}, {
id: 3,
title: 'Delhi'
}, {
id: 4,
title: 'Mumbai'
}],
maps: [{
id: 1,
title: 'Zoo',
city_id: 1
}, {
id: 2,
title: 'Palace',
city_id: 1
}, {
id: 3,
title: 'Beach',
city_id: 4
}]
}];
});
Plunker here https://plnkr.co/edit/r1S1e61H3RfH3uYGYTBP?p=preview
Can anyone please help me.
Move the coordinates to the $scope:
$scope.coordinates = {
lat: 28.620089858889145,
lng: 77.17483520507812
};
And:
<ng-map zoom="13" center="{{coordinates.lat}},{{coordinates.lng}}" ...
Use ng-change on the select:
ng-change="centerCity(citySelect.selectedOption)"
In the centerCity method you can use the geocoder to retrieve the coordinates by city name. Then you simply need to update the variables.
Simple example:
var geocoder = new google.maps.Geocoder();
$scope.centerCity = function(city) {
geocoder.geocode({
'address': city.title
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.$apply(function() {
$scope.coordinates.lat = results[0].geometry.location.lat();
$scope.coordinates.lng= results[0].geometry.location.lng();
});
} else {
console.log('Error');
}
});
};
Demo: https://plnkr.co/edit/WETs0FL0DbPbDn2A77hq?p=preview

UI Bootstrap Typeahead is not displaying the values returned async

I am trying to do an autocomplete search using UI Bootstrap Typeahead to select a data from a database.
My service returns data in my response, but data are not listed in the component.
When I put a breakpoint in the component code , the list is there and when I continue to debug the list is displayed, but if it runs without breakpoints , the list is not displayed.
HTML
<input id="inputInstalation"
ng-model="profile.instalation"
typeahead-editable="false"
typeahead="installation as installation.name for installation in searchInstallation($viewValue)"
typeahead-input-formatter="formatLabel($model)"
ng-required="true">
Controller
$scope.searchInstallation = function(text){
return $http.get('/api/installations/name/' + text).then(function(response){
return response.data;
});
};
$scope.formatLabel = function(model){
return model ? model.name : "";
};
API NodeJS - DB Mongo
exports.findByName = function(req, res){
var connection = getConnection();
var Installation = getInstallationModel(connection);
Installation.find({name: new RegExp(req.params.name, "i")}, function (err, result) {
connection.close();
if(err) throw err;
res.json(result);
});
};
Response
[{ _id: 5525662b74100eb40f13ce00,
name: 'test 2',
description: 'Gdoc 02.02.00-00',
__v: 0,
services:
[ { name: 'Alfresco',
context: '/alfresco',
parameterURL: 'prmGdocServiceUrl',
_id: 5525662b74100eb40f13ce03 },
{ name: 'ri-rest',
context: '/iserver',
parameterURL: 'prmUrlIntegrationServer',
_id: 5525662b74100eb40f13ce02 },
{ name: 'ldap',
parameterURL: 'prmLdapUrl',
parameterUser: 'prmLdapPrincipal',
parameterPassword: 'prmLdapPassword',
_id: 5525662b74100eb40f13ce01 } ],
tables:
[ { _id: 5525662b74100eb40f13ce06, name: 'esegsistema' },
{ _id: 5525662b74100eb40f13ce05, name: 'esegusuario' },
{ _id: 5525662b74100eb40f13ce04, name: 'XPTO' } ],
parameters:
[ { name: 'prmUrlBaseServidorHTTP',
systemCode: '314',
_id: 5525662b74100eb40f13ce0e },
{ name: 'prmTamanhoMaximoArquivo',
systemCode: '314',
_id: 5525662b74100eb40f13ce0d },
{ name: 'prmGdocServiceUrl',
systemCode: '314',
_id: 5525662b74100eb40f13ce0c },
{ name: 'prmLdapUrl',
systemCode: '314',
_id: 5525662b74100eb40f13ce0b },
{ name: 'prmLdapPrincipal',
systemCode: '314',
_id: 5525662b74100eb40f13ce0a },
{ name: 'prmLdapPassword',
systemCode: '314',
_id: 5525662b74100eb40f13ce09 },
{ name: 'prmDomainSufix',
systemCode: '314',
_id: 5525662b74100eb40f13ce08 },
{ name: 'xxxxx',
systemCode: '314',
_id: 5525662b74100eb40f13ce07 } ] }]
I found the problem, I'm using the https://github.com/McNull/angular-block-ui and it conflicts with the component.
Solution : I created a requestFilter from angular blockui to don't block requests sent the component to API .

geting json inventory id using resource

i cant get and ID from my json api, how can i do that? I am doing like $scope.info.id in my delete function but id doesnt work like that.
Here is my delete function
app.controller('InventoryCtrl', function($scope, $http, Inventory, $location) {
//getting the objects from Inventory
$scope.info = Inventory.query();
$scope.deleteInv = function () {
Inventory.drop({id: $scope.info.id}, function() {
$location.path('/');
});
};
});
here is my factory
app.factory('Inventory', function($resource, $http) {
return $resource('http://localhost/api/v1/inventory/:id', {id: "#id"},
{
drop: {
method: 'DELETE',
params: {id: "#id"}
}
}
);
});
And here is my api
{
meta: {
limit: 20,
next: null,
offset: 0,
previous: null,
total_count: 3
},
objects: [
{
category: {},
count: 1,
created: "2014-02-28T11:54:02.831409",
description: "dasdasdasdsa",
id: 20,
location: "asd",
name: "adas11",
resource_uri: "/api/v1/inventory/20",
status: "sad"
},
{
category: {},
count: 1,
created: "2014-02-28T11:54:03.708003",
description: "dasdasdasdsa",
id: 21,
location: "asd",
name: "adas11",
resource_uri: "/api/v1/inventory/21",
status: "sad"
},
]
}
I don't think you should call "drop" function. Instead you should call the 'delete' function which you specified in your factory.
$scope.deleteInv = function () {
Inventory.delete({id: $scope.info.id}, function() {
$location.path('/');
});

Resources