I am learning Angluarjs's $resource. I set a button on HTML for deleting a record from a json file,and hope to delete one record from testForm.json file. Unfortunately, I failed to do so and can't solve the problem.
The codes are here: my Angularjs code
The deleting function in controller codes is shown as follows
$scope.deleteRecord = function () {
var id = 1;
var arecord = new singleResource();
arecord.$get({userId:id},function () {
$log.info(arecord);
arecord.$delete();
});
The HTML part of the deleting function is shown here:
<div class="form-group">
<div class="col-sm-6 col-sm-push-2">
<button type="button" class="btn btn-primary" ng-click="deleteRecord()">Delete information</button>
</div>
</div>
"$scope.deleteRecord" is the function that when clicking the Delete information button, the record with id=1 in json file should be removed. The error says:"DELETE http://localhost:3000/contactInfo 404 (Not Found) :3000/contactInfo:1 ", while the "arecord" is shown as an object in the log "m {email: "333#333", password: 321, method: "Internet", id: 1, $promise: undefined…}", which should be fine.
$http
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
$http is built into Angular, so there’s no need for the extra overhead of loading in an external dependency. $http is good for quick
retrieval of server-side data that doesn’t really need any specific
structure or complex behaviors. It’s probably best injected directly
into your controllers for simplicity’s sake.
$resource
The action methods on the class object or instance object can be invoked >with the following parameters:
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
$resouce is good for situations that are slightly more complex than $http. It’s good when you have pretty structured data, but you
plan to do most of your crunching, relationships, and other operations
on the server side before delivering the API response. $resource
doesn’t let you do much once you get the data into your JavaScript
app, so you should deliver it to the app in its final state and make
more REST calls when you need to manipulate or look at it from a
different angle.
Alternatively you could use: restangular https://github.com/mgonto/restangular
Restangular is a perfect option for complex operations on the client side. It lets you easily attach custom behaviors and interact
with your data in much the same way as other model paradigms you’ve
used in the past.
Angularjs guide: https://docs.angularjs.org/api/ng/service/$http#delete
try with the delete method:
$scope.deleteRecord = function () {
var id = 1;
var arecord = new singleResource();
arecord.$delete({userId:id},function () {
$log.info(arecord);
//arecord.$delete();
});
or
$http({
method: 'DELETE',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I hope it helps.
Related
I have an Inbox with internal messages from my clients. When I click on the list over the name I'm requesting using jQuery $.ajax so:
$.ajax({
url: 'messages/retrieve/' + client_id,
}).done( function(data) {
$('.messages-dialog').html(data);
});
My controller should return a variable with json data? I understand it should dump it on a view and I should treat it there but how to do it if is client side?
I don't know if is better to treat and create the html structure into controller and than just load it in .messages-dialog with jQuery.html();
Sorry I'm a little lost on that issue.
You can use jQuery.ajax() method, as in the example above. Also see the official documentation with examples http://api.jquery.com/jquery.ajax/.
Besides you can use jQuery.get() and jQuery.post() methods depending on how and what you will send. You can use this methods as shown below:
var url = 'messages/retrieve/' + client_id;
$.post( // for example
url,
function( data ) {
$('.messages-dialog').html(data);
});
See official documentation with examples here: http://api.jquery.com/get/, http://api.jquery.com/jQuery.post/.
Server handler should be like as below:
use JsonResponse; // you must specify the exact component (I use this)
/**
* Change message in dialog // for example
*/
public function changeDialogMessageAction(Request $request) {
// request data processing
$response = new JsonResponse();
$response->setData(array(
// new data for returning to client
));
return $response; // your data, which will be handled in callback
}
You shouldn't create HTML structure in the controller. It's bad style! JavaScript has asynchronous event model, and you should use it. Controller must handle / transform data, which were passed by you and then return back. jQuery callback must embed received handled / transformed data in DOM.
I am working with a NodeJs App and I have to call to a online web service in the logic part.
The problem is that if that web service is taken down, the whole system stop working.
To deal with this I have though in use a Facade pattern, adding another web service with the same functionality, and one offline file with similar information (but not as good as the web service's).
The idea is call the Facade (javaScript file?) from the logic part. It has to choose first the primary web service and call it, if it is down, go for the second one, and if it is also down, call the offline data file.
Any idea about how to stucture this on NodeJS?
This is a possible solution
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl1'
}).then(function (response) {
// this callback will be called asynchronously
// when the response is available
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// In case it fails
$http({
method: 'GET',
url: '/someUrl2'
}).then(function (response) {
// this callback will be called asynchronously
// when the response is available
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// If it fails again, use JSON file here
});
});
I want to make a HTML using javascript to do the following task:
loading a HTML such as here
put the stock price value in a variable
display using that variable for calculation
You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you to do that. Your only option should be making a server-side call then do whatever you want
Contact that provider and request/buy access to their information. They might provide you with an endpoint of a Web API (or other service). You can then access it through (for instance) AngularJS:
// Simple GET request example:
$http({
method: 'GET',
url: 'http://somehosturl/api/stockprices/' // or whatever
}).then(function successCallback(response) {
$scope.stockPrices = response;
}, function errorCallback(response) {
HandleError(response);
});
(based on their general usage sample)
webApp.factory('userAPIService', ['$resource',
function ($resource) {
return $resource(
"/api/reportconfig/:Id",
{Id: "#Id" },
{
// at some point change methods from GET to POST and DELETE
"update": {method: "PUT"},
"getreport": {'method': 'GET', 'params': { Id:'getReportbyReportID', expire: 'true', cache:'false'}, isArray: true},
"createreport": {'method': 'GET', 'params': { Id:'createreport', expire: 'true', cache:'false'}},
"listreport": {'method': 'GET', 'params': { Id:'listreport', expire: 'true', cache:'false'}, isArray: true},//requre user_uuid
"deletereport": {'method': 'GET', 'params': { Id:'deletereport', expire: 'true', cache:'false'}}
}
);
}]);
The above code get called with the following command
userAPIService.createreport({
'report_config_json': report_config_json, topic_uuid: topic.uuid, report_id: reportID, user_id:userid }, {'Id': 'createreport'})
I'm having a hard time understanding what the userAPIService actually returns when called, an object? what does it return when I call userAPIService.createreport? How/when are the arguments passed to it?
With only the limited information I have above, here is what I believe is taking place in your code:
First, you are creating a factory, which is similar to a service, except you get multiple instances as opposed to a singleton (a one-time creation that every module can get via injection)
When you use the userAPIService factory in your code, you are being returned a function (which in this scenario could act like a constructor.) I can't tell without seeing the context of your use of userAPIService, but I would assume you are creating a local variable called 'userAPIService' which is being initialized to the results of a call to userAPIService().
At this point you have an instance of a userAPIService which appears to just be an data retrieval service (not to be confused with an Angular Service, which is a singleton)
your call to userAPIService.createreport() will initially return an empty object or array (noted in the docs at the bottom of this answer.) it will then make the specified $http call to the URL (from $resource definition) via the Method (from the $resource definition) and attempt to retrieve the data you are looking for. Once it has completed that request, it will then populate the reference that was just created with the actual data returned.
Since your factory creates custom actions to be taken via $resource we will look at that definition to determine what will take place when you call .createreport():
"createreport": {'method': 'GET', 'params': { Id:'createreport', expire: 'true', cache:'false'}}
This line tells $resource how to handle requests using the createreport() method. It says that when this method is called, it will make a request to the $resource object's URL via GET. It will pass default values of expire:true and cache:false as well as Id:'createreport' which will be used to populate the URL (Unless an Id is specified in your method call - which it is), since it requested an Id object via :Id at the end.
Now, when you made the actual method call, you specified two objects to pass to the $resource request, the first will then be used to basically override the default parameter values that were specified when you create the $resource method. The second will be passed as headers along with the $http request that $resource will then make.
For even more information, I would highly recommend that you read the documentation: https://docs.angularjs.org/api/ngResource/service/$resource
Currently I have a resource like so:
return $resource(usersUrl, {}, {
//The data model is loaded via a GET request to the app
query: {method: 'GET', params: {}, isArray: false},
putupdate: {method: 'PUT', params:{}}
});
Now I would like to put some JSON that looks like:
{"providerid":"userpass","firstname":"t","lastname":"b","fullname":"t b","email":"emailaddress,"avatarurl":"http:/.....","passwordset":true}
Anyway as you can see it doesn't have a top level name, if I pass this information in as a parameter to the resource a name is appended to the json like:
myparam:{"providerid":"userpass","firstname":"t","lastname":"b","fullname":"t b","email":"emailaddress,"avatarurl":"http:/.....","passwordset":true}
Is there a away of preventing this from happening as the server side doesn't like it?
Thanks
Tom
From your question it sounds like you are trying to use $resource to post some arbitrary json data. If this data is not a Resource() you should simply use $http.
$http.put(theUrl, theJsonData);
If it is actually a Resource() you can just call the method you declared when building your resource.
myResource.putupdate();