Angular CRUD parsing ID on resource remove - javascript

I'm trying to write a function to remove an answer:
// Remove an answer
$scope.removeAnswer = function(answer) {
Answers.remove(answer._id);
};
However, I am throwing the console error:
DELETE http://localhost:9000/api/answers?0=5&1=4&10=7&11=4&12=2&13=c&14=0&15=0&16=0&17=0&18=0&19=0&2=7&20=0&21=0&22=0&23=4&3=3&4=d&5=0&6=1&7=4&8=2&9=d 404 (Not Found)
When I console.log(answer._id), I get a reasonable id like 348374831...
Why is it converting the id to a weird format and how can I fix it?
Here seems to be an identical question, although the answer doesn't really explain the problem: AngularJS resource - encoding url string parameter as an array

The corect way to do it is:
$scope.removeAnswer = function(answer) {
Answers.remove({
id: answer._id
});
};
or instead of id use the corect name you used in the $resource factory definition.
Example:
var User = $resource('/user/:userId', {userId:'#id'});
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});
$resource expects object parameter. Here's an example in Angular docs

Related

Catch oData errors from oTable.bindItems

I have a table built up in JavaScript thus:
oTable.bindItems({
path: oQuery,
template: this.getFragment("<fragment>"),
filters: aFilter
});
Is there a way to catch the errors coming back from the odata call in the same way when you do an oModel.read you can specify success and error functions?
This reference seems to not mention it: https://sapui5.hana.ondemand.com/#docs/api/symbols/sap.ui.base.ManagedObject.html#bindAggregation
Perhaps there is something I am missing.
We have 2 methods to check for oData Failure:
attachMetadataFailed. (https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.model.odata.ODataModel.html#attachMetadataFailed)
attachRequestFailed.
Let's take up option 2 with an example ( as I'm sure you will have a valid oData Service).
Service: http://services.odata.org/Northwind/Northwind.svc/
Note: Employees is a valid Entity Set in the above Northwind service.
I will try to bind my table with a wrong Enity set name such as : MyEmployees.
Now, binding my table to MyEmployees will throw error which we need to catch. Below is the working code:
View:
<Table items = "{/MyEmployees}">
Controller:
var url = "proxy/http/services.odata.org/Northwind/Northwind.svc/";
var oDataModel = new sap.ui.model.odata.ODataModel(url);
oDataModel.attachRequestFailed(function(e) {
console.log('request failed');
});
this.getView().setModel(oDataModel);
Go ahead and try it. Let me know if this helps. :)

Check contents of response to json request?

I am trying to build a random quote generator as per the FreeCodeCamp challenge, but I wanted to begin by just writing a test to confirm I'm actually getting the json object I'm requesting. I have a simple h1 element with the id set to 'quote' and the following code (jQuery is loaded up in the CodePen)
function genQuote () {
var output = $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(data){
var theQuote = data.content;
var Author = data.title;
document.getElementById('quote').innerHTML = theQuote;
});
}
The url in question, when visited, shows what looks plainly like a json object, to me, but my function does not change the #quote item at all.
Remove &callback= from URL, to request JSON, instead of converting $.getJSON() call to jsonp request. Also, an array is returned, not a plain object; access the object using bracket notation
function genQuote () {
var output = $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(data){
var theQuote = data[0].content;
var Author = data[0].title;
document.getElementById('quote').innerHTML = theQuote;
})
}
$(genQuote);
jsfiddle https://jsfiddle.net/gpyx6jLy/
As the comment to your question says, this is a Cross Origin Request Sharing (CORS) issue. The API is returning "http://null" as the Access-Control-Allow-Origin header, which disallows your access.
It looks like this is a bug in their API server, and you probably won't be able to use it.

Angular accessing $scope objects with dynamic names

I have an angular controller whereby I'm trying to look through a list of strings, querying an ajax query for each string within the list. The code is as follows:
var itemsliststrings = ["department", "year", "project", "subdepartment"];
itemsliststrings.forEach(function (itemStr) {
$http.post("/Budget/GetListBudget", { budgetType: itemStr })
.success(function (data) {
var the_string = itemStr;
var model = $parse(the_string);
model.assign($scope, data);
$scope.$apply();
})
.error(function (error) {
console.error(error);
toastr.error('An error occured, unable to load ' + itemStr);
});
});
This is the code that doesn't work. it complains with the error '$parse' is undefined. I took this example from a SO post.
I basically want to be able to loop through my itemsliststrings, post the string to an web method, and set the return data for this to a model variable called that particular string. So when I take the "department" string, I submit this string to the web method, I get a data object back, which I then set to the $scope.department object.
Thanks
Have you tried just $scope[itemStr] = data?
Did you inject the $parse provider in your controller?
.controller('yourController',function($scope,$parse,etc..){});

AngularJS how to make a POST JSON

I'm trying to make a post but below does not appear to work it does not post but console.log() looks like a put request i.e
http://127.0.0.1/api/v1/participant?account=%7B%22pk%22:1%7D&email=someemail#gmail.com
factory
app.factory('CbgenRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://127.0.0.1');
});
});
controller
$scope.participant = {email :$scope.email, password: "", account:{pk:1}};
CbgenRestangular.all('api/v1/participant').post("participant", $scope.participant);
What I'm I doing wrong?
according to the documentation (https://github.com/mgonto/restangular#lets-code):
// First way of creating a Restangular object. Just saying the base URL
var baseAccounts = Restangular.all('accounts');
var newAccount = {name: "Gonto's account"};
// POST /accounts
baseAccounts.post(newAccount);
note that post has a single input
you can add 'api/v1' to your base address - there's no need to carry it around (https://github.com/mgonto/restangular#setbaseurl)
I would also suggest using the plural form for a resource route, but that's a convention that some people don't follow - I guess it is a matter of taste

$.get with dynamic data names?

I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});

Categories