Angularjs : $resource encapsulate the json into an object - json

I have a $resource called Livres I need to send to my API that wait a json typed like this :
{livres: {
id: 1
name: "bidule"
}}
This is the resource :
angular.module('TestApp').factory('Livres', [
'$resource', function($resource) {
return $resource('api/v1/livres/:id', {
id: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
And the called method to save :
$scope.addLivres = function() { //create a new livres. Issues a POST to /api/livress
$scope.livres.$save(function() {
$state.go('adminLivres'); // on success go back to admin home i.e. adminLivres state.
});
};
This only send a json like
{id: 1
name: "bidule"}
How can I make the json send to be encapsulated into a livres {} ?

Related

Change JSON structure to send in API post request

I am making an API POST call in Angular 8. I have to send a JSON object in the call which should be of structure:
-{}JSON
-{}data
-[]exp
+{} 0
+{} 1
but I am sending data in this format:
-[]JSON
+{} 0
+{} 1
in my typescript I am getting two objects {}0, {}1 in array called: receivedData then I am storing the data like:
this.changedData = this.receivedData;
this.postService.postMethod(this.headers, this.changedData)
in my postService:
postMethod(header, changedData): Observable<any[]> {
return this.http.post<any>(`the url here`, changedData, {headers: header, responseType: 'text' as 'json'})
.pipe(map(response => {
return response;
}))
}
how to send data in the mentioned format? I want the json structure of changedDetails to be as mentioned on the top with the same naming convention like: {}data and []exp How can I push receivedData objects into exp[] which I can then send into data{} which will then be entirely pushed into changedDetails {}
Just so we're on the same page, I'm imagining you're receiving data with the following shape:
[ { ... }, { ... } ]
And you want to transform it to this shape:
{
data: {
exp: [ { ... }, { ... } ]
}
}
(Let me know if this is not the case.)
If this is correct, than the transformation is quite straightfoward: simply create a new object literal like so:
this.changedData = {
data: {
exp: this.receivedData,
},
};

Alfresco webscript: AJAX, JSON

I've successfully created a webscript to that returns a JSON response. See below:
get.js file:
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath("PATH");
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + " not found.";
status.redirect = true;
}
// construct model for response template to render
model.folder = folder;
get.json.ftl:
{"corporates" : [
<#recurse_macro node=folder depth=0/>
]
}
<#macro recurse_macro node depth>
<#list node.children?sort_by(["properties","name"]) as child>
{
"Name" : "${child.properties.name}",
"URL" : "${child.url}",
"serviceURL" : "${child.serviceUrl}",
"shareURL" : "${child.shareUrl}",
"ID" : "${child.id}",
"Type" : "${child.typeShort}"
},
<#if child.isContainer>
{
<#recurse_macro node=child depth=depth+1/>
}
</#if>
</#list>
</#macro>
This returns JSON cleanly (woohoo!), but I would like to grab the JSON from a second webscript using AJAX.
Currently, I am utilizing a typical AJAX call in my second webscript's get.html.ftl file like this:
$(document).ready(function() {
$('.submit-button').click(function(e) {
// Avoid to trigger the default action of the event.
e.preventDefault();
// Actions declared here...
$.ajax({
type: 'GET',
dataType: 'html',
url: 'PLACEHOLDER_URL_PATH',
success: function(data) {
// Shows the result into the result panel.
$('#alfresco-result').html(data);
alert('Done.');
},
error: function(data) {
// Shows the result into the result panel.
$('#alfresco-result').html("ERROR");
}
});
});
})
My question is why the AJAX call doesn't work when I use dataType: 'json'?
I would like to parse through the JSON in my AJAX call and turn it into html (e.g. an html list), but it's not accepting the JSON dataType as an acceptable input.
Any help is appreciated!
You can use POST Webscript Call using ajax like this and pass your jsonObject
dataObj:"yourJsonObject",
to dataObject
Alfresco.util.Ajax.jsonPost(
{
url: Alfresco.constants.PROXY_URI + "sample/mypostwebscript",
dataObj:"yourJsonObject",
successCallback: {
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
// Display error message and reload
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
},

Outputting JSON Data from Local Web Server onto Ionic App using Angular

CHALLENGE
I am trying to output the following JSON via Angular JS into my Ionic Framework Starter Side-Menu App and currently the only response that I get from my Console Log is the following:
0 825606 log ApiEndpoint, [object Object]
1 825809 log Got some data: , [object Object]
1 825883 log Got some data: , [object Object]
Unfortunately as a result of this, I'm unable to display my product list within products.html
JSON Output from my Web Server [node.js server with MongoDB database local]
My webserver output is available at http://localhost:8080/api/products
[
{
_id: "55be0d021259c5a6dc955289",
name: "Apple",
price: 2.5
},
{
_id: "55be0d541259c5a6dc95528a",
name: "Oranges",
price: 1.5
},
{
_id: "55be0d6c1259c5a6dc95528b",
name: "Pear",
price: 3
},
{
_id: "55be0d6c1259c5a6dc95528c",
name: "Orange",
price: 3
}
]
services.js
angular.module('starter.services', [])
.factory('Api', function($http, ApiEndpoint) {
console.log('ApiEndpoint', ApiEndpoint)
var getApiData = function() {
return $http.get(ApiEndpoint.url + '/products')
.then(function(products) {
console.log('Got some data: ', products);
return products;
});
};
return {
getApiData: getApiData
};
})
controllers.js [Relevant code]
.controller('ProductsCtrl', function($scope,Api) {
$scope.products = null;
Api.getApiData()
.then(function(result) {
$scope.products = result.products;
})
ionic.project
{
"name": "grocerApp",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://cors.api.com/api"
}
]
}
products.html [to show off the output]
<ion-view view-title="The Grocer Shop">
<ion-content>
<ion-list>
<ion-item ng-repeat="product in products">
<a class="item item-thumbnail-left" href="#/app/products/{{product.id}}">
<img src="http://loremflickr.com/30/30/apples">
<h2>{{product.name}}</h2>
<p>EUR {{product.price}} per kilogram</p>
</a>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
app.js [Relevant code]
angular.module('starter', ['ionic', 'starter.controllers','starter.services'])
.constant('ApiEndpoint', {
url: 'http://localhost:8080/api'
})
Unfortunately the following links did not help me out :
Ionic/Angular App not reading json data from api
Getting data from a json file in IONIC using AngularJS
I also double checked the file path and the JSON loads well in my local browser window[I am using Chrome with CORS extension enabled - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en ]
QUESTION
How can I get my JSON Data from my local webserver into my products.html file?
your service and controller is a bit wrong try the following
services.js
angular.module('starter.services', [])
.factory('Api', function($http, ApiEndpoint) {
console.log('ApiEndpoint', ApiEndpoint);
var getApiData = function() {
return $http.get(ApiEndpoint.url + '/products');
};
return {
getApiData: getApiData
};
})
controllers.js
.controller('ProductsCtrl', function($scope,Api) {
$scope.products = null;
Api.getApiData().then(function(result) {
$scope.products = result.data;
});
EDIT: Further explanations
So your first problem was returning a promise and trying to resolve it in multiple places.
return $http.get(ApiEndpoint.url + '/products')
.then(function(products) {
console.log('Got some data: ', products);
return products;
});
Api.getApiData()
.then(function(result) {
$scope.products = result.products;
})
Best practice is that your service returns the promise, which $http already does. You should then handle how that promise is resolved in the controller so basically what I did was just remove the .then from your factory.
The next error you had was trying to call result.products inside then function. How a promise resolves is nesting the entire body in a json object with the data attribute. So in this case your response is looking like {'data': [array_of_fruit]}. If your response were to return {'products':[array_of_fruit]} then you would still have to access like result.data.products.
Hope this helps.

extjs error on filling store

I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});
The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]

ExtJs, how to send JSON on store.load() using POST method

I need to send JSON object during read operation on store. Headers and method are set correctly.
var proxyDefinition = {
type : 'rest',
api : {
read : '/some/url'
},
actionMethods : {
create : 'POST',
read : 'POST',
update : 'PUT',
destroy : 'DELETE'
},
reader : {
type : 'json'
}
};
var store = Ext.create('Ext.data.Store', {
proxy : proxyDefinition,
model : 'SomeModel'
});
// this needs to send JSON
store.load({
params : {
filter: [] // some filtering rules
}
});
Problem is that POST body is sent as url encoded query string, not JSON object with property "filter".
ExtJs version 4.2.2
It is likely that you are looking for proxy config option paramsAsJson:true