I am new to angular and trying to consume a basic back end service that I created using laravel. It is a basic Todo application and I am trying to fetch all the users resource for now.
If you go to the following URI, it will give back the all the users in the application:
Link to the URI
The code in my angular file looks like
var testing = angular.module('testing', []);
testing.controller('MainCtrl', function($scope, $http){
$scope.hello = "Hello World!";
$http.get('users.json').success(function(data){
$scope.users = data;
});
});
Now when I pass the URI in the parameter of $http.get method, I don't see any data. I have tried {{ users | json }} in my main index file to see the dump output. It simply doesn't work. But when I copy just the data array in the response and save it to a json file, it works perfectly.
Now the json that is returned from the web service has slightly more information like status and messages. How do I remove them when fetching them in Angular so that it works or is there a way I can have them returned and then extract them somehow from the whole data that has been returned?
If here http://todoapi.rohanchhabra.in/users is response from your server you should update your $http call to :
$http.get('users.json').success(function(response){
$scope.users = response.data;
});
if you requesting json file from your local iis make sure that it can serve .json files
Related
Im writing an PWA in Svelte with Routify and im trying to save notes (containing id, title and a body) in a local json file.
Ive been following this code from Svelte REPL (Svelte POST example), but they use an web URL. When trying to use a direct link i get a 404, even tho the path is correct.
<script>
let foo = 'title'
let bar = 'body'
let result = null
async function doPost () {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
body: JSON.stringify({
foo,
bar
})
})
const json = await res.json()
result = JSON.stringify(json)
}
</script>
<input bind:value={foo} />
<input bind:value={bar} />
<button type="button" on:click={doPost}>
<p>Post it.</p>
</button>
<p>Result:</p>
<pre>
{result}
</pre>
I installed a json server plugin, which kinda worked, but i want to store the data as a local file.
Is it possible to write, using POST to a local json file without using any server?
Is it possible to use relative path when using fetch? Or should i use something else?
Generally, you don't POST data anywhere else but to a server. Having said that, if you absolutely want to save your data using POST, you can add a serviceworker to your app that intercepts the fetch() request and then saves the data in cache, indexeddb, localstorage or something like this. But having that serviceworker in between just for that is a bit silly, you should rather store the data directly in cache, indexeddb or localstorage.
Example for localstorage:
const data = { someKey: { someOtherKey: 'some value' } };
localStorage.setItem('myData', JSON.stringify(data));
Be aware though that, no matter which kind of storage you're using, they all might be wiped out if the user decides to clear browser data or if the browser cleans up by itself due to storage shortage.
I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.
I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' });
});
My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:
var item = Product.query().$promise.then(function(promise) {
console.log(promise) // successfully returns JSON objects
});
However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.
This is the error that I get:
http://localhost:3000/api/products.json/12-34 404 (Not Found)
I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?
Here is my data structure:
[
{
"id": "12-34",
"name": "Greece",
"path": "/images/athens.png",
"description": ""
},
...
]
By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.
Then configure your $resource instance to use the proper verb like this :
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' }, {'update': { method:'PUT' }});
});
check $resource docs for more info.
NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db.
Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.
You probably don't implement POST method for urls like /api/products.json/12-34. POST method is requested from angular for saving a new resource. So you need to update your server side application to support it and do the actual saving.
app.factory('Product', function($resource) {
return $resource('api/products.json/:id', { id: '#id' });
});
Try adding "/:id" at the end of the URL string.
I am new to Angular and I am trying to build a simple todo application using it. I have designed a module called TodoServices in which I am creating a User service using the factory method. The code looks something like:
angular.module('TodoServices', ["ngResource"])
.factory('User', function($resource){
return $resource('http://todoapi.rohanchhabra.in/users/:id');
});
The code in my app.js looks like:
var angularApp = angular.module('angularApp', ['TodoServices']);
angularApp.controller('UsersController', function(User){
this.users = {};
this.users = User.query();
});
When I run my application, I get this error: Error link
I think this is because my web service is returning an object which not only has the data but also has a few other things such as a status and messages. Now Is it a wrong way of doing it? Should I just return the array from the back end? What is the actual problem here and how to solve this?
As your error link says:
By default, all resource actions expect objects, except query which expects arrays.
You should use an other function like User.Get() when you're not expecting an array but just a single object.
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.
I have the following situation:
I use ngResource to save some data to the mysql database and after the successfull save() I want to log the json response the server sends to me:
Document.save({}, postData, function(response){
console.log(response);
});
This does not result in a simple response, but in something like an object with its own methods. I want some smple output like the response.data after an $http.$get:
{
"docClass":"testets",
"colCount":1,
"columns":null,
"groupid":7,
"id":19,
"lang":"de",
"title":"test",
"version":1409849088,
"workflow":"12234"
}
Greets
Check out this answer
Promise on AngularJS resource save action
So I think in your case you need to do
var document = new Document(postData);
document.$save()
.then(function(res){});
But also from the link I provided
This may very well means that your call to $save would return empty reference. Also then is not available on Resource api before Angular 1.2 as resources are not promise based.