I'm making a mobile app using ionic (based on the AngularJS framework) where I want to display data from a RESTfull API. I'm pretty new to AngularJS so I'm not familiar with the best practices. I want to get data from this API but with a weeknumber parameters in the URL so I can get data from specific weeks. I have looked especially to the example of the AngularJS website.
This is what I have in my services:
var eventServices = angular.module('starter.services', ['ngResource']);
eventServices.factory('EventServiceAPI',['$resource',
function($resource) {
return $resource('http://localhost:8080/schedulingAPI/plannedevents?weeknumber=:weeknumber', {}, {
query: { method: 'GET', params:{weeknumber:'weeknumber'}, isArray: true}
});
}]);
This is what I have in my controller to get the API data:
$scope.events = EventServiceAPI.get({weeknumber: 7});
However, I still keep getting the error:
Error: [$resource:badcfg] object
When I use the full API URL in services and $scope.events = EventServiceAPI.query() in my controller, the full API-data is displayed without error.
I also don't get where to put the parameters; in the brackets after the resource URL or the params option in the query method.
Edit:
The output of http://localhost:8080/schedulingAPI/plannedevents?weeknumber=:weeknumber
[{"id":2985,"event":{"eventId":589,"subject":"Masterproef","year":2014,"weekNumber":7,"dayNumber":6,"startHour":8,"startMinute":10,"endHour":12,"endMinute":45,"startTime":"2014-02-14T07:10:00Z","endTime":"2014-02-14T11:45:00Z","classgroups":[{"id":8,"name":"4ELICTI"},{"id":4,"name":"4ENAU"},{"id":10,"name":"4ELICTE"},{"id":1,"name":"4CHB"},{"id":3,"name":"4ENEL"},{"id":9,"name":"4EMEM"},{"id":2,"name":"4CHC"},[]],"teacher":null},"rooms":[{"id":24,"abbr":"D015"}]},{"id":4021,"event":{"eventId":604,"subject":"Bedrijfsbeleid 2 hc","year":2014,"weekNumber":7,"dayNumber":6,"startHour":8,"startMinute":10,"endHour":9,"endMinute":35,"startTime":"2014-02-14T07:10:00Z","endTime":"2014-02-14T08:35:00Z","classgroups":[{"id":6,"name":"4ELICT"},[]],"teacher":null},"rooms":[{"id":44,"abbr":"G120"}]}]
Replace params:{weeknumber:'weeknumber'} with params:{weeknumber:'#weeknumber'}, notice the #.
If the parameter value is prefixed with # then the value of that
parameter is extracted from the data object (useful for non-GET
operations).
From angular documentation
And call your function with query:
$scope.events = EventServiceAPI.query({weeknumber: 7});
Actually, you can simplify your resource declaration like this:
eventServices.factory('EventServiceAPI',['$resource',
function($resource) {
return $resource('http://localhost:8080/schedulingAPI/plannedevents');
});
}]);
Angular will automatically append the query string for you
Related
I'm new to AngularJs. How to save data from Api into couchdb using AngularJs and retrieve it back. Can anyone give example coding.
'Cause CouchDB has a REST interface you can use these AngularJS services to access its functionalities:
$resource
$http
Eventually here is a tutorial with a step-by-step example:
http://thewebhacker.com/rapid-app-prototyping-with-angularjs-and-couchdb/
Refer this dummy code, this will basically calls URL defined by Couch and returns JSON data,
function getItems () {
$http.get(appSettings.db + '/_design/expenses/_view/byName')
.success(function (data) {
$scope.items = data.rows;
});
}
getItems();
For more info, plz refer this link:
http://www.sitepoint.com/tracking-expenses-couchdb-angular/
I have a form in angular where a user enters various criteria which I then want to pass to Web Api and get a result after queries are run. I originally thought of this as a "Get" but had trouble passing complex objects to the Web Api. With some advice, I then used a Post and was able to pass the criteria run the query in the Web Api but I had trouble getting the result back in Angular. The Web Api method is run and gets the results. But I don't see the results in the data service.
What is the best approach where the criteria for a query is multiple fields and some are lists? I haven't been able to find any good examples.
Here is the Web Api method:
[HttpPost]
public IEnumerable Post([FromBody] FrequentPawnerReportCriteria criteria)
{
var repo = new FrequentPawnerReport();
var result = repo.GetReport(criteria);
return result;
}`
Here is the dataservice:
function getFrequentPawner(criteria) {
return $http.post("/api/FrequentPawner/Post", criteria)
.then (getFrequentPawnerComplete)
.catch(getFrequentPawnerFailed);
function getFrequentPawnerComplete(response) {
var x = response
return response.data.results;
}
function getFrequentPawnerFailed(error) {
alert("XHR failed for frequent pawner report: " + error.responseText);
}
}
And here is the controller code:
function getTopPawnerResults(criteria) {
return DataContext.getFrequentPawner(criteria)
.then(
function (result) {
vm.frequentPawnerReport = result.data;
return vm.frequentPawnerReport;
});
}
Simply use JSON. Use JSON.stringify() to parse JSON object to string and POST it. Similarly, return JSON string from server, and assign it to variable in Angular. It will be automatically converted to JSON object.
I think when you make your post request, you need to have a callback function that would get invoked when your Web Api returns. Within that callback function you can update your $scope variables which will make your web ui show the response from the server. You can find an example of what I mean here: https://docs.angularjs.org/api/ng/service/$http
The gist of it:
$http({
method: 'POST',
url: '/path/to/your/web/api',
function(success) {
console.log('Successfully executed the api call');
$scope.response = response; // change this to match the data you are expecting from the server response
},
function(failure) {
console.error('There was an error');
$scope.failure = failure; // change this to match your failure response
}
);
Thanks for responding. The project is a mix of web forms and angularjs. I am migrating the app and didn't notice this form had a conflict which was causing a post back and making it look like the result was not being returned. I took the form into a separate project and was able to get the results I was going for.
i have an angular application that calls web api . it was working all fine with web api controller and ngresource until i required to get count of results.
to get just the count of a result i need to use $inlinecount which only seems to be working with oDataController . with oDataControlelr in place my promises dont work.
$scope.totalCount = storeCommandResource.query({ $inlinecount: "allpages", $top: 0 });
i get
Error: [$resource:badcfg] query
please guide.
its look like i can use oDatacontroller with a model builder setup like this
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<StoreCommand>("StoreCommandsRest");
config.Routes.MapODataServiceRoute(routeName: "OData", routePrefix: "api", model: builder.GetEdmModel());
config.AddODataQueryFilter();
and all i needed to change was query to get
$scope.totalCount = storeCommandResource.get({ $inlinecount: "allpages", $top: 0 });
then i am reading my returned count like
response["odata.count"]
I am using Restangular on my front-end and I want to query this URL:
http://localhost:4000/study?projectId=123456
It returns a list of studies associated to a certain project. So I have the following controller code for the moment:
MyApp.controller('ProjectDetailCtrl', function ($scope, $routeParams, Restangular) {
// [...]
var resource = Restangular.all('study');
console.log($routeParams.projectId); // displays "123456", the current projectId
resource.getList('study', {projectId: $routeParams.projectId}).then(function(studies){
// Doing stuff
});
});
But it does not return the data I want. Indeed, when I look in the Network panel of Firefox, it queries http://localhost:4000/study, as if the parameter was not specified...
It seems to be the same code that the author give on Github, and every question on the web seems to use the same syntax. Why is my parameter ignored?
The first parameter of the getList should be your query params. You've already specified the study bit of your url. You had an extra "study".
var resource = Restangular.all('study');
resource.getList({ projectId: $routeParams.projectId }).then(function(studies) {
// do stuff
});
I am trying to do a get request to recover data from the server using the following url:
url = /api/projects/:projectId/scenarios
How can I do that using $http.get in AdngularJS?.
you might want to take a look at Restangular, I like its notation more than standard angularjs $http or $resource.
Restangular.setBaseURL('/api/');
Restangular.one('projects', projectId).all('scenarios').getList().then(function(data) {
myVariable = data;
});
Restangular