confused between loading json on routes or on models - json

I'm new at emberjs and I'm starting to learn how it works,
what is the difference when specifying the json on routes or on models
model: function() {
var url = 'https://api.github.com/repos/emberjs/ember.js/pulls';
return Ember.$.getJSON(url).then(function(data) {
return data.splice(0, 4);
});
},
this is how i call the json on routes , now my problem , what is the use of this function
export default DS.RESTAdapter.extend({});

The DS.RESTAdapter is part of ember-data. You can use ember-data to load your json from a rest api. It is how ever very opinionated about said api. I don't believe it will work out of the box with the github api you are calling.
If I were you I'd focus on getting to grips with emberjs and when you feel you're getting comfortable with it you can expand your focus to include ember-data.

Related

Umbraco 7 route to custom Controller for rest API

i want to map a Route to an ApiController, to post data to it.
I'm not using a Surface contoller, since i want a clean url like /api/test/{action}, without the umbraco/surface part in url.
I'm trying to use
RouteTable.Routes.MapHttpRoute(
"ApiTest",
"Api/Test/{action}",
new
{
controller = "Api_Test",
action = "Search"
});
But i'm getting an error since MapHttpRoute need a 4th string[] parameter.
How can i Map that route?
Then i will post a json or xml and return the response (json or xml).
Use RouteTable.Routes.MapRoute instead. I've used that previously in Umbraco sites and it works fine, e.g.
RouteTable.Routes.MapRoute(
name: "cookie-api-location",
url: "cookie-api/setregioncheckcookie/",
defaults: new
{
controller = "Cookie",
action = "SetRegionCheckCookie"
}
);

Send a queryset of models from Django to React using Ajax

I've been looking for info about this for hours without any result. I am rendering a page using React, and I would like it to display a list of Django models. I am trying to use ajax to fetch the list of models but without any success.
I am not sure I understand the concept behind JSon, because when I use the following code in my view:
data = list(my_query_set.values_list('categories', 'content'))
return JsonResponse(json.dumps(data, cls=DjangoJSONEncoder), safe=False)
It seems to only return a string that I cannot map (React says that map is not a function when I call it on the returned object). I thought map was meant to go through a JSon object and that json.dumps was suppose to create one...
Returned JSon "object" (which I believe to just be a string):
For the time being I have only one test model with no category and the content "At least one note "
[[null, "At least one note "]]
React code:
$.ajax({
type:"POST",
url: "",
data: data,
success: function (xhr, ajaxOptions, thrownError) {
var mapped = xhr.map(function(note){
return(
<p>
{note.categories}
{note.content}
</p>
)
})
_this.setState({notes: mapped})
},
error: function (xhr, ajaxOptions, thrownError) {
alert("failed");
}
});
Can someone please point me to the best way to send Models from Django to React, so I can use the data from this model in my front end?
I recommend using the Django REST Framework to connect Django to your React front-end. The usage pattern for DRF is:
Define serializers for your models. These define what fields are included in the JSONified objects you will send to the front-end. In your case you might specify the fields 'categories' and 'content.'
Create an API endpoint. This is the URL you will issue requests to from React to access objects/models.
From React, issue a GET request to retrieve a (possibly filtered) set of objects. You can also set up other endpoints to modify or create objects when receiving POST requests from your React front-end.
In the success function of your GET request, you will receive an Array of Objects with the fields you set in your serializer. In your example case, you would receive an Array of length 1 containing an object with fields 'categories' and 'content.' So xhr[0].content would have the value "At least one note ".
In your code, the call to json.dumps within the JsonResponse function is redundant. Check out the docs for an example of serializing a list using JsonResponse. If you are serializing the object manually (which I don't recommend), I'd use a dictionary rather than a list -- something like {'categories': <value>, 'content' : <value>}. DRF will serialize objects for you like this, so the fields are easier to access and interpret on the front-end.

Angular2 HTTP Providers, get a string from JSON for Amcharts

This is a slightly messy questions. Although it appears I'm asking question about amCharts, I really just trying to figure how to extract an array from HTTP request and then turn it into a variable and place it in to 3-party javacript.
It all starts here, with this question, which was kindly answered by AmCharts support.
As one can see from the plnker. The chart is working. Data for the chart is hard coded:
`var chartData = [{date: new Date(2015,2,31,0,0,0, 0),value:372.10,volume:2506100},{date: new Date(2015,3,1,0, 0, 0, 0),value:370.26,volume:2458100},{date: new Date(2015,3,2,0, 0, 0, 0),value:372.25,volume:1875300},{date: new Date(2015,3,6,0, 0, 0, 0),value:377.04,volume:3050700}];`
So we know the amCharts part works. Know where the problem is changing hard coded data to a json request so it can be dynamic. I don't think this should be tremendously difficult, but for the life of me I can't seem figure it out.
The first issue is I can't find any documentation on .map, .subscribe, or .observable.
So here is a plunker that looks very similar to the first one, however it has an http providers and injectable. It's broken, because I can't figure out how to pull the data from the service an place it into the AmCharts function. I know how pull data from a http provider and display it in template using NgFor, but I don't need it in the template (view). As you can see, I'm successful in transferring the data from the service, with the getTitle() function.
this.chart_data =_dataService.getEntries();
console.log('Does this work? '+this.chart_data);
this.title = _dataService.getTitle();
console.log('This works '+this.title);
// Transfer the http request to chartData to it can go into Amcharts
// I think this should be string?
var chartData = this.chart_data;
So the ultimate question is why can't I use a service to get data, turn that data into a variable and place it into a chart. I suspect a few clues might be in options.json as the json might not be formatted correctly? Am I declaring the correct variables? Finally, it might have something to do with observable / map?
You have a few things here. First this is a class, keep it that way. By that I mean to move the functions you have inside your constructor out of it and make them methods of your class.
Second, you have this piece of code
this.chart_data =_dataService.getEntries().subscribe((data) => {
this.chart_data = data;
});
What happens inside subscribe runs asynchronously therefore this.chart_data won't exist out of it. What you're doing here is assigning the object itself, in this case what subscribe returns, not the http response. So you can simply put your library initialization inside of the subscribe and that'll work.
_dataService.getEntries().subscribe((data) => {
if (AmCharts.isReady) {
this.createStockChart(data);
} else {
AmCharts.ready(() => this.createStockChart(data));
}
});
Now, finally you have an interesting thing. In your JSON you have your date properties contain a string with new Date inside, that's nothing but a string and your library requires (for what I tested) a Date object, so you need to parse it. The problem here is that you can't parse nor stringify by default a Date object. We need to convert that string to a Date object.
Look at this snippet code, I used eval (PLEASE DON'T DO IT YOURSELF, IS JUST FOR SHOWING PURPOSES!)
let chartData = [];
for(let i = 0; i < data[0].chart_data.length; i++) {
chartData.push({
// FOR SHOWING PURPOSES ONLY, DON'T TRY IT AT HOME
// This will parse the string to an actual Date object
date : eval(data[0].chart_data[i].date);
value : data[0].chart_data[i].value;
volume : data[0].chart_data[i].volume;
});
}
Here what I'm doing is reconstructing the array so the values are as required.
For the latter case you'll have to construct your json using (new Date('YOUR DATE')).toJSON() and you can parse it to a Date object using new Date(yourJSON) (referece Date.prototype.toJSON() - MDN). This is something you should resolve in your server side. Assuming you already solved that, your code should look as follows
// The date property in your json file should be stringified using new Date(...).toJSON()
date : new Date(data[0].chart_data[i].date);
Here's a plnkr with the evil eval. Remember, you have to send the date as a JSON from the server to your client and in your client you have to parse it to a Date.
I hope this helps you a little bit.
If the getEntries method of DataService returns an observable, you need to subscribe on it to get data:
_dataService.getEntries().subscribe(
(data) => {
this.chart_data = data;
});
Don't forget that data are received asynchronously from an HTTP call. The http.get method returns an observable (something "similar" to promise) will receive the data in the future. But when the getEntries method returns the data aren't there yet...
The getTitle is a synchronous method so you can call it the way you did.

AngularJS service PUT to flat JSON file

This is perhaps a stupid question. In which case I apologize.
I know you can use http.get to read flat JSON files, but is there any way to use a flat JSON file in a angular service to mimic a database for other CRUD operations. This would be very basic and only in development. I plan on using django rest, firebase, or something similar, but wanted to focus on the front end first.
You can use $httpBackend service from the ngMockE2E to mock a complete backend with post, get, put, and so on.
I've included the example from the angular documentation for the sake of completeness:
myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
myAppDev.run(function($httpBackend) {
var phones = [{name: 'phone1'}, {name: 'phone2'}];
// returns the current list of phones
$httpBackend.whenGET('/phones').respond(phones);
// adds a new phone to the phones array
$httpBackend.whenPOST('/phones').respond(function(method, url, data) {
var phone = angular.fromJson(data);
phones.push(phone);
return [200, phone, {}];
});
$httpBackend.whenGET(/^\/templates\//).passThrough();
//...
});

PUT requests with Custom Ember-Data REST Adapter

I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.