Store new values into JSON - angularjs

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.

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);
});
})

Image uploading from angularjs 1.5 to grails 3 as byte[] and save it in postgresql as bytea

I have searched for a solution in several days now. There are many examples where people is trying to upload a picture.
I really need some help to come trough this. I have some code here and I hope someone could push me to through this.
I have added my code in this link
//Angularjs controller :
self.createVaerksted = function(id, navn, by, nummer, billede) {
var data = {};
data.vaerkstedNavn = navn;
data.byNavn = by;
data.vaerkstedNummer = nummer;
data.myImage = billede[0];
vaerkstedService.createVaerksted(data)
.then(function(response) {
console.log(response)
})
// Angularjs service
var prefix = 'http://localhost:8080/api/';
createVaerksted: function(data) {
return $http.post(prefix + 'saveVaerksted', data)
}
Thank you in advance
To upload a file (image, xls, etc) with AngularJS you can use a FormData.
For example, using Angular profile you can create a angular controller:
function UploadExcelController(domainServiceFactory, contextPath, $log, $state, $stateParams) {
var vm = this;
vm.contextPath = contextPath;
var UploadExcel = domainServiceFactory('/api/uploadExcel/:id', {id: '#id'}, {
create: {
method: "POST",
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
});
vm.uploadExcel = function(data){
var fd = new FormData();
fd.append("year", data["year"]);
fd.append("excelFile", data["excelFile"][0]);
$log.info(fd)
UploadExcel.create({}, fd).$promise.then(function (res) {
$state.go('dashboard');
}).catch(function (err) {
$log.info("error "+err);
alert(""+err);
throw err;
});
}
Create a Grails Command:
class UploadExcelCommand implements Validateable {
MultipartFile excelFile
Integer year
static constraints = {
year nullable: false
excelFile validator: { val, obj ->
if ( val == null ) {
return false
}
if ( val.empty ) {
return false
}
['xlsx'].any { extension ->
val.originalFilename?.toLowerCase()?.endsWith(extension)
}
}
}
and do the bussiness logic in the controller:
class UploadExcelController {
static responseFormats = ['json', 'xml']
def save(UploadExcelCommand cmd) {
if( cmd.hasErrors() ) {
render 404
return
}
if( Excel.get(cmd.year) ){
render 404
return
}
println cmd.year
println cmd.excelFile.inputStream
render "OK"
}
}

How to add inner array to JSON object for saving to Mongodb?

$scope.createProduct = function () {
console.log("inside createProduct click")
console.log($scope.Product);
console.log($scope.selectedGroups);
$http.post('Product/CreateProduct', $scope.Product).success(function (response) {
console.log(response);
console.log(response.success);
if (response.success == true) {
$scope.status = "Successfully Created Product";
$mdDialog.hide();
}
});
};
Above is my posting code. I want to add "$scope.selectedGroups" to $scope.Product
For Eg:
$scope.Product = {
"ProductName": "FirstProduct",
"ContentLink: "SampleLink"
"SelectedGroups":{"one"},{"two"},{"three"}
}
Here "SelectedGroups"= $scope.selectedGroups
How to append this from controller

Elasticsearch.js AngularJS autocomplete

I'm trying to implement an autocomplete feature using Elasticsearch, angularJS and bootstrap.
I've got inspired by this solution :
autocomplete/typeahead angularjs bootstrap on elasticsearch
This is my Angular code:
angular.module('cineAngularApp')
.service('client', function (esFactory) {
return esFactory({
host: 'localhost:9200',
apiVersion: '2.2',
log: 'trace'
});
});
angular.module('cineAngularApp')
.controller('AutocompleteCtrl', function ($scope,client) {
$scope.getResult = function(val){
return client.search({
index: 'autocomplete_test',
fields: 'city',
q: 'city:'+val
}).then(function (resp) {
var keywords = [];
for(var i in resp.hits.hits){
var fields = (resp.hits.hits[i]).fields["city"];
keywords.push(fields);
}
return keywords;
}, function (err) {
console.trace(err.message);
});
};
});
Here is my problem
The above code works fine when I use a simple query, but as soon as I change the query by adding body it doesn't work.
angular.module('cineAngularApp')
.controller('AutocompleteCtrl', function ($scope,client) {
$scope.getResult = function(val){
return client.search({
index: 'autocomplete_test',
fields: 'city',
body: {
query: {
match: {
city: val
}
}
}
}).then(function (resp) {
var keywords = [];
for(var i in resp.hits.hits){
var fields = (resp.hits.hits[i]).fields["city"];
keywords.push(fields);
}
return keywords;
}, function (err) {
console.trace(err.message);
});
};
});
I don't know if it can help but I've also noticed when debugging that it's not a POST request anymore but it's an OPTION one.
Thanks in advance for your help.
Try with this:
return client.search({
index: 'movies',
"fields": [ "title" ],
"body": { // Use body field on elasticsearch client library
"query": {
"query_string": {
"fields": ["title"],
"query": "title:"+val
}
}
}
}).then(function (resp) {
// ....
})

How to get the data as a promise while saving?

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");
});
}
}
})

Resources