I am using Angurlar.js to call my Web API and I am getting error as:
P01:1 Uncaught SyntaxError: Unexpected token : and in resources tab it is being shown that these braces should not be there {"ProductID1":"P01","ProductName1":"Pen","Quantity1":10,"Price1":12.0} kindly help me
this is my angular code:
var app = angular.module('store', []);
app.controller('StoreController', ['$http', '$scope', function ($http, $scope) {
$scope.display = function () {
// $http.get('http://localhost:17279/api/Product/GetProduct/' + $scope.pid).success(function (data) {
$http({
method: 'jsonp',
url: 'http://localhost:17279/api/Product/GetProduct/' + $scope.pid,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).success(function (data) {
{{data}}
});
}
}]);
below code is in my WebAPI controller
List<Product> productList = new List<Product>{
new Product{ProductID1="P01",ProductName1="Pen",Quantity1=10,Price1=12},
new Product{ProductID1="P02",ProductName1="Copy",Quantity1=12,Price1=20},
new Product{ProductID1="P03",ProductName1="Pencil",Quantity1=15,Price1=22},
new Product{ProductID1="P04",ProductName1="Eraser",Quantity1=20,Price1=27},
};
public List<Product> GetProductList()
{
return productList;
}
public IHttpActionResult GetProduct(string id)
{
var product = productList.FirstOrDefault(
(p) => p.ProductID1 == id);
if(product == null)
{
return NotFound();
}
return Ok(product);
}
Apart from this I have a product model class in WebAPI which has 4 members and their properties namely : price,quantity,productID,productname
Remove the {{data}} in your success callback. This is angular's way of binding expressions to view and should not be used within your javascript code
$scope.display = function () {
$http({
method: 'jsonp',
url: 'http://localhost:17279/api/Product/GetProduct/' + $scope.pid,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).then(function (data) {
$scope.data = data;
});
}
Related
I'm creating a js object with the same properties as my controller action expects as parameters.
controller.js
(function () {
'use strict';
angular
.module('app')
.controller('requestController', requestController);
requestController.$inject = ['$scope', 'lecturesFactory', 'attendeesFactory'];
$scope.setSelectedLectures = function () {
var lecture1, lecture2;
for (var i = $scope.lectures.length - 1; i >= 0; i--) {
var lecture = $scope.lectures[i];
if (lecture.selected === true) {
if (lecture1 == null) {
lecture1 = lecture.lectureId;
}
else {
lecture2 = lecture.lectureId;
}
}
}
attendeesFactory.setSelectedLectures($scope.emailAddress.text, lecture1, lecture2).then(function (data) {
$scope.showInvalidUserMessage = true;
$scope.message = data.message;
});
};
activate();
function activate() { }
}
})();
attendessFactory.js
(function () {
'use strict';
angular
.module('app')
.factory('attendeesFactory', attendeesFactory);
attendeesFactory.$inject = ['$http'];
function attendeesFactory($http) {
var service = {
setSelectedLectures: setSelectedLectures
};
return service;
function setSelectedLectures(emailAddress, lecture1, lecture2) {
var promise = $http({
method: 'POST',
url: '/Home/SetSelectedLectures',
data: {
emailAddress: emailAddress,
lecture1: lecture1,
lecture2: lecture2
}
}).then(function (response) {
console.log(response);
return response.data;
});
return promise;
}
}
})();
And my MVC Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SetSelectedLectures(SelectedLectureData data)
{
// ...
}
}
public class SelectedLectureData
{
public String EmailAddress { get; set; }
public int Lecture1 { get; set; }
public int? Lecture2 { get; set; }
}
I've tried what some posts on StackOverflow suggested, such as using JSON.stringify, changing the content-type, but I still get the parameter values null (even if I put them directly in the action, instead of using a custom class).
Use [FromBody] anotation to make it working which will serialize data in SelectedLectureData model.
public IActionResult SetSelectedLectures([FromBody]SelectedLectureData data)
Otherwise you need to do
var promise = $http({
method: 'POST',
url: '/Home/SetSelectedLectures',
data: JSON.strigify({ "data": {
emailAddress: emailAddress,
lecture1: lecture1,
lecture2: lecture2
}})
})
Try updating your javascript to
function setSelectedLectures(emailAddress, lecture1, lecture2) {
var model = {
emailAddress: emailAddress,
lecture1: lecture1,
lecture2: lecture2
};
var data = JSON.strigify(model);
var promise = $http({
method: 'POST',
url: '/Home/SetSelectedLectures',
data: data
}).then(function (response) {
console.log(response);
return response.data;
});
return promise;
}
and using [FromBody] attribute on controller action
[HttpPost]
public IActionResult SetSelectedLectures([FromBody]SelectedLectureData data)
{
// ...
}
JSON property name should be same as class properties else it will take it as null
function setSelectedLectures(emailAddress, lecture1, lecture2) {
var promise = $http({
method: 'POST',
url: '/Home/SetSelectedLectures',
data: {
EmailAddress : emailAddress,
Lecture1: lecture1,
Lecture2: lecture2
}
}).then(function (response) {
console.log(response);
return response.data;
});
I am trying to send a DELETE command using $http.delete but am getting an error:
TypeError --> Cannot create property 'method' on string 'user_id=5&response=This+is+a+test.'
when I execute the command in the controller as follows:
In the controller:
.controller(myController', function($scope) {
var something = {
user_id: 1,
text: 'This is a test.'
}
MyFactory.deleteSomething(something);
});
In the service:
.factory('MyFactory', function($http) {
var service = {};
service.deleteSomething = function(something) {
var data = $.param(something);
var promise = $http.delete('http://example.com/myapp.php?',
data, {
headers: {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.success(function(data,status) {
console.log("Delete success!");
return data;
})
.error(function(data, status, header, config) {
console.log("Delete FAILED!");
});
return promise;
}
return service;
});
What am I missing here?
The second parameter delete() expects is an object with http request configuration. Not some string as you are passing data:
$http.delete('http://example.com/myapp.php?',
data, {
[...]
I am creating an email application that makes RESTful calls to Google APIs. I am using AngularJS and Java. I have had some success so far but I am unable to delete an email because I keep getting this error: TypeError: object is not a function.
My Angular knowledge is limited.
In my html I call the function deleteEmail and pass an email id.
Here is the controller:
app.controller('InboxController', function($rootScope, $scope, $cookies,
$location, InboxService) {
$rootScope.loggedIn = true;
$scope.emails = InboxService.getMessages().success(function(jsonData) {
$scope.emails = jsonData;
});
$scope.deleteEmail = function(id) {
$scope.id = {
'id' : id
};
// Parse to JSON
var responseJSON = angular.toJson($scope.id);
// Make call to InboxService
var response = InboxService().del(responseJSON).success(
function(jsonData) {
response = jsonData;
if (response == 'success') {
alert('Message deleted');
} else {
alert('Message not deleted');
}
});
}
});
The method $scope.emails works fine. It is the $scope.deleteEmail that is giving the error.
Here is the service:
app.factory('InboxService', function InboxService($http) {
var exports = {};
// Get a list of all emails
exports.getMessages = function() {
return $http.get('resources/inbox/get').error(function(data) {
console.log('There was an error!', data);
});
};
// Delete an email
exports.del = function(id) {
console.log('id ' + id);
return $http({
method : 'POST',
url : 'resources/inbox/delete',
data : id,
headers : {
'Content-Type' : 'application/json'
}
});
};
return exports;
});
I don't think I am getting as far as the service though. The problem seems to be with the controller.
Console output:
TypeError: object is not a function
at Scope.$scope.deleteEmail (http://localhost:8080/NewProject/js/controllers.js:64:18)
at Parser.functionCall (http://localhost:8080/NewProject/bower_components/angular/angular.js:10903:21)
at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:8080/NewProject/bower_components/angular/angular.js:19259:17)
at Scope.$get.Scope.$eval (http://localhost:8080/NewProject/bower_components/angular/angular.js:12811:28)
at Scope.$get.Scope.$apply (http://localhost:8080/NewProject/bower_components/angular/angular.js:12909:23)
at HTMLButtonElement.<anonymous> (http://localhost:8080/NewProject/bower_components/angular/angular.js:19264:23)
at http://localhost:8080/NewProject/bower_components/angular/angular.js:2853:10
Pls be sure you called deleteEmail(id) from within html with right syntax without $scope
I got it working. I changed the Controller delete method to this:
$scope.delete = function (id) {
InboxService.delete(id).success(function() {
$scope.loadInbox();
});
};
And the Service method to this:
// Delete an email
exports.delete = function(id) {
console.log('id ' + id);
return $http({
method : 'DELETE',
url : 'resources/inbox/delete',
data: id,
headers : {
'Content-Type' : 'application/json'
}
});
}
I am trying to retrieve some sample values from mysql database and display it to my view using angularjs. I am pretty new to angular and I am trying to use $http.get to get my data. The following is my code
Angular Code
angular
.module('sampleApp.service.product', [])
.factory('productsService', [
'$http',
function ($http) {
return {
getProducts: function () {
// return $http.get("/Home/GetTweets");
return $http({
method: 'GET',
url: '/api/Products'
}).success(function (data) {
alert("success");
alert(data);
}).error(function (error) {
//Showing error message
alert("failed");
$scope.status = 'Unable to retrieve products' + error.message;
});
alert(data) returns [object,Object]
My Controller code has the following
public class productsController : ApiController
{
public IEnumerable<Product> Get()
{
ProductEntities context = new ProductEntities();
var _products = from p in context.Products.AsEnumerable() select p;
return _products;
}
}
On debug I am getting the values in DB int the _products. Please help me out.Thanks In advance!
enter code here
your code is successful as i can see
put console.log(data); instead of alert(data); and then you can see the data in the browser console.
.factory('productsService', [ '$http','$q', function ($http,$q) {
return {
getProducts: function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/api/Products'
}).success(function (data) {
deferred.resolve(data);
}).error(function (error) {
deferred.reject(data);
});
return deferred.promise;
}
}
In the Conteroller,
productsService.getProducts().then(function(data) {
//success
$scope.products = data.rows;
console.log($scope.products);
}, function() {
//flier
});
I have a web api which returns IHttpActionResult(myCollection) on Get.
My angular JS controller is has a function :
$scope.loadcollection = function($defer, params) {
console.log("inside loadcollection ");
mySvc.getCollection().then(function(myCollection) {
//$defer.resolve(myCollection);
$scope.recievedCollection= myCollection
console.log("invoices are : ", $scope.recievedCollection);
});
My service in angular JS is as follows :
app.factory('mySvc', ['$resource', '$q', 'serviceHelperSvc',
function($resource, $q, serviceHelper) {
var myObject= serviceHelper.collectionObj;
var getCollection= function() {
/* var d = $q.defer();
var resp = Invoice.query();
console.log("resp is : ", resp);
d.resolve(true);
return d.promise;*/
return myObject.query();
};
}]);
my serviceHelperSvc is as follows:
app.factory('serviceHelperSvc', ['$http', '$resource',
function($http, $resource) {
var config = {
"apiurl": "http://localhost:8000/"
}
var baseUrl = config.apiurl;
var buildUrl = function(resourceUrl) {
return baseUrl + resourceUrl;
};
var addRequestHeader = function(key, value) {
};
return {
AuthorizationToken: $resource(buildUrl("Token"), null, {
requestToken: {
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}
}),
collectionObj: $resource(buildUrl('api/CollectionObj/:CollectionObjId'), {
CollectionObjId: '#Id'
}, {
'update': {
method: 'PUT'
}
})
};
}
]);
when i try to run this, i get undefined is not a function at mySvc.getCollection().then(function(myCollection)
before then(function(myCollection).
when i try using the defer promise approach, i get an exception at the same place saying $promise is not defined