Can't access the specified url using rest and angularjs - angularjs

I am trying to get data using REST api from html form using angularjs and do some db operation on it. I am getting 404 error for the rest link specifid.
Here's my js code
var app=angular.module("myApp",[]);
app.controller("mycon",function($scope,$http){
console.log("entered here");
$scope.test={};
$scope.add = function() {
console.log("entered here");
var json=JSON.stringify($scope.test);
console.log($scope.test);
console.log(json);
$http({
url: "rest/xyz/role",
method: "GET",
data: json,
headers: {'Content-Type': 'application/json'}
})
.success(function(data, status,header,config) {
$scope.data = data;
}).error(function(data, status,header,config) {
alert("error");
});
}});
<body ng-app="myApp" ng-controller="mycon">
<center>
<h2> Login Here! </h2>
<hr/>
<form >
<table>
<tr>
<td>Signum Id:</td>
<td><input type="text" ng-model="test.sig"/></td>
</tr>
<tr>
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</tr>
</table>
</form>
</center>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
</body>
and my REST code goes here.
#Path("/xyz")
public class RestServices {
#GET
#Path("/role")
#Produces({ "application/json" })
public String list() {
//do db operation
}
}
After deploying and running the project on server, I am getting following error:
http://localhost:8080/LoginEmployee/rest/xyz/role "404 NOT FOUND".

Add servlet mapping in web.xml as "rest/*". and also check the project name which should be "LoginEmployee"

Try removing rest/ from $http param.
url: "xyz/role",

Related

model does not change angularjs

I have client list in a table.
When I click on editClient, the name of the client will be displayed in an input text. This work perfectly.
<body ng-app="myClientApp" ng-controller="myClientController">
<a class="btn btn-success" ng-click="chargerClients()">
Charger Clients
</a>
<div ng-if="clients">
<table>
<tr ng-repeat="cl in clients >
<td>{{cl.idClient}} </td>
<td>{{cl.nomClient}} </td>
<td> <a class="btn btn-success" ng-click="editClient(cl.idClient,cl.nomClient)"></td>
</table>
<div>
<input type="text" ng-model="id">
<input type="text" ng-model="nom">
<button ng-click="modifyClient()"> validate</button>
</div>
</div>
</body>
The problem is when I click on modifyClient, it keeps the same values and nothing happens. How can I fix this problem?
<script>
var app=angular.module("myClientApp", []);
app.controller("myClientController", function($scope,$http,$window) {
$scope.chargerClients=function(){
$http.get("/clients")
.success(function(data){
$scope.clients=data;
});
};
//load id and name
$scope.editClient=function(idClient, nomClient){
$scope.id=idClient;
$scope.nom=nomClient;}
//modifyClient
$scope.modifyClient=function(){
var params="";
var params = ({
idClient:$scope.id,
nomClient: $scope.nom});
$http({
method: 'PUT',
url: "clients",
data: params,
headers: {'Content-type': 'application/json'}
})
.success(function(data) {
$window.alert($scope.id+$scope.nom);
$scope.chargerClients();
$window.location.href = '/index.html'
})
};
}
</script>
Try using POST method in your modifyClient
Thank you i solve it; i have to add link in ng-model:
`<ng-model="client.id">`
and in the script also:
$scope.client={}
$scope.editClient=function(idClient, nomClient){
$scope.client.id=idClient;
}
$scope.modifyClient=function(){
var params="";
var params = ({
idClient:$scope.client.id
});

$http.get(...).success is not a function

So I'm working on a small app with angular 1 with file uploading and I found out that there were changes that I wasn't aware of as the way coding https in a controller is different now. As the old way now causes http.get.success is not a function. I need help understanding what changes from 1.4 angular 1 to the current version that I have to do now with my controllers so my data from my rest API show up on my HTML. As I'm getting $http.get(..).success is not a function error now.
gallerycontroller
var galleryCtrl = angular.module('galleryCtrl', []);
galleryCtrl.controller('galleryController', function($scope, $http) {
$scope.superheroes= [];
//Retrieve all the superheroes to show the gallery
$http({
method: 'GET',
url: '/superhero'
})
.success(function (data, status, headers, config) {
console.log(data);
})
.error(function (data, status, headers, config) {
console.log(data)
})
});
gallery.html
<!-- view the gallery of all the superheroes in the db -->
<div class="row">
<div ng-repeat="superhero in superheroes">
<div class="col-md-4 col-xs-6 col-sm-offset-0">
<div class="thumbnail">
<img ng-src="{{superhero.picture.url | fpConvert: {filter:'sharpen', w:300, h:150} }}" />
<div class="caption text-center">
<h3>{{superhero.name}}</h3>
<p><label>Super powers: </label> {{superhero.superPowers}}</p>
<div class="text-right"><a ng-href="/#/detail/{{superhero._id}}" class="btn btn-danger" role="button">View</a> </div>
</div>
</div>
</div>
</div>
</div>
Success is deprecated. Use then.
$http.get().then(function success(result){
}, function error(err) {
})

Not able to get the data from asp.net mvc controller to angularjs using ajax call

i am able to hit the controller method and able to return the data
[HttpPost]
public JsonResult GetAppsList()
{
var Apps = DataModel.ApplicationMasters.ToList();
return Json(new { appslist = Apps });
// return AppsList;
}
but in angular js not able to get the data
myApp.controller('SpicyController', ['$scope','$http', function ($scope,$http) {
$http({
method: 'POST',
url: 'Home/GetAppsList'
}).then(function (response) {
$scope.appslist = response.data.appslist; }, function (error) {console.log(error);});}]);
in view
<div class="main" ng-app="spiceApp">
<div ng-controller="SpicyController">
<table>
<tr ng-repeat="app in appslist">
<td>
{{app.Name}}
</td>
</tr>
</table>
</div>
</div>
can you help me why i am not able to display result?
<div class="main" ng-app="spiceApp">
<div ng-controller="SpicyController">
<table>
<tr ng-repeat="(index,data) in appslist">
<td>
{{data.Name}}
</td>
</tr>
</table>
</div>
</div>
applist is an Object . To Apply ng-repeat on an Object write this ng-repeat=(index,data) in applist.
myApp.controller('SpicyController', ['$scope','$http', function ($scope,$http) {
$http({
method: 'POST',
type:'json',
url: 'Home/GetAppsList'
}).then(function (response) {
$scope.appslist = response.data.appslist; }, function (error) {console.log(error);});}]);

AngularJS FORM POST

I came across a situation where I need to call server method before continue with the FORM POST in angularJS. If the server method returns an error I need to display it and remain in the same method which ultimately does not do the POST request.
How can I achieve this with AngularJS?
See my code sample below
HTML
<form action="http://app.test.com/ProcessTransaction" method="POST">
<table>
<tr>
<td><input type="hidden" name="Amount" value="25.00" /></td>
</tr>
<tr>
<td><input type="hidden" name="Currency" value="NZD" /></td>
</tr>
</table>
<div class="container-fluid align:left">
<button type="submit" class="btn btn-success" ng-disabled="properties.disabled" ng-click="ctrl.action()">{{properties.label}}</button>
</div>
</form>
Angular Controller
this.action = function action() {
var req = {
method: method,
url: <some_url>,
data: angular.copy(data_to_sent),
params: params
};
return $http(req)
.success(function(data, status) {
$scope.properties.dataFromSuccess = data;
})
.error(function(data, status) {
$scope.properties.dataFromError = data;
})
.finally(function() {
});
}
Okay based on the question OP want's to validate the form and then go for submitting the form values.There are two approaches here
1) Do the form validation on client side using <ng-form> / <form> and required in the input fields.
2) We can skip the traditional way of form submit and just call our submit function on submit click and validate the form from server and if it's success then go for saving the form value or else display errors.
Make below changes for approach (2) as it will be closest for you question.
In HTML
<form>
<table>
<tr>
<td><input type="hidden" name="Amount" value="25.00" /></td>
</tr>
<tr>
<td><input type="hidden" name="Currency" value="NZD" /></td>
</tr>
</table>
<div class="container-fluid align:left">
<button type="submit" class="btn btn-success" ng-disabled="properties.disabled" ng-click="ctrl.action()">{{properties.label}}</button>
</div>
</form>
In JS
this.action = function action() {
var req = {
method: method,
url: <some_url>,
data: angular.copy(data_to_sent),
params: params
};
return $http(req)
.success(function(data, status) {
$scope.properties.dataFromSuccess = data;//here data can contain whether the form is valid or invalid...so create a boolean at server if it's valid or not..
if($scope.properties.dataFromSuccess.isSuccess){
$http.post(URL,formData).success(function(data){
$scope.dataSaved = data;
});
}else{
$scope.properties.dataFromError = data; //set the errors in the scope to display
}
})
.error(function(data, status) { //this error means request has been failed to process not the validation error we are checking at server..
//$scope.properties.dataFromError = data;
})
.finally(function() {
});
}

AngularJS - Upload Image to SharePoint Library/Corrupted File

I am using the following Angular Module to attempt to upload images to SharePoint through a Web browser: https://github.com/nervgh/angular-file-upload
I am getting successful 200 POST messages and a file is being uploaded... However, it is not showing the image itself in the preview or opening of the image, but rather an [X]. I am guessing this is related to how the content is encoded, but unsure of what to do next. Here is my controller:
appControllers.controller('appUploadImageCtrl', ['$scope', '$location', 'FileUploader', function ($scope, $location, FileUploader) {
var uploader = $scope.uploader = new FileUploader({
url: "/sites/_api/web/lists/getByTitle('Images')/RootFolder/Files/add(url='test.jpg',overwrite='true')",
processData: false,
transformRequest: angular.identity,
headers: {
'Accept': 'application/json;odata=verbose', 'content-type': undefined, 'X-RequestDigest': $("#__REQUESTDIGEST").val() }
});
// FILTERS
uploader.filters.push({
name: 'imageFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter,
options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function (fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function (addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function (item) {
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function (fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function (progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function (fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function (fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function (fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function () {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
$scope.cancel = function () {
$location.path('/');
}
}]);
HTML:
<div class="col-md-3">
<h3>Select files</h3>
<div ng-show="uploader.isHTML5">
<!-- 3. nv-file-over uploader="link" over-class="className" -->
<div class="well my-drop-zone" nv-file-over="" uploader="uploader">
Base drop zone
</div>
<!-- Example: nv-file-drop="" uploader="{Object}" options="{Object}" filters="{String}" -->
<div nv-file-drop="" uploader="uploader" options="{ url: '/foo' }">
<div nv-file-over="" uploader="uploader" over-class="another-file-over-class" class="well my-drop-zone">
Another drop zone with its own settings
</div>
</div>
</div>
<!-- Example: nv-file-select="" uploader="{Object}" options="{Object}" filters="{String}" -->
Multiple
<input type="file" nv-file-select="" uploader="uploader" multiple /><br />
Single
<input type="file" nv-file-select="" uploader="uploader" />
</div>
<div class="col-md-9" style="margin-bottom: 40px">
<h3>Upload queue</h3>
<p>Queue length: {{ uploader.queue.length }}</p>
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th ng-show="uploader.isHTML5">Size</th>
<th ng-show="uploader.isHTML5">Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploader.queue">
<td><strong>{{ item.file.name }}</strong></td>
<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
<div>
<div>
Queue progress:
<div class="progress" style="">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.progress + '%' }"></div>
</div>
</div>
<button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">
<span class="glyphicon glyphicon-upload"></span> Upload all
</button>
<button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel all
</button>
<button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">
<span class="glyphicon glyphicon-trash"></span> Remove all
</button>
</div>
</div>
The problem with your code is that you are trying to upload your image as a normal byte array, which isn't possible when you are uploading to libraries through the SharePoint REST API.
To be able to upload non-text files to SharePoint, they have to be uploaded as a base64 encoded byte array.
Your options are to either use another Angular module such as Angular-Base64-Upload, or to encode the image file before you upload it using your first choice of file upload module.
In case you go for option two, you can encode the image using the following technique, though how it will work with your selected file uploader, I cannot say. It appears you can modify the file attribute of the FileItem in the file uploader, so it should not be that hard.
Encoding the image file to a base64 binary arraybuffer
//Create a new FileReader object
var reader = new FileReader();
reader.onload = processImage;
//Read the file as a base64 encoded string
reader.readAsDataURL(input.files[0]);
function processImage () {
//The image file has been read by the filereader
//and can be converted to an arraybuffer
var arrayBuffer = base64ToBinary(this.result);
//Upload the image to the SharePoint images library
uploadImage(arrayBuffer);
}
function base64ToBinary (base64EncodedFile) {
var BASE64_MARKER = ';base64,';
var base64Index = base64EncodedFile.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = base64EncodedFile.substring(base64Index);
var raw = atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(rawLength);
for (i = 0; i < rawLength; i++)
{
array[i] = raw.charCodeAt(i);
}
return array.buffer;
}
When I wrote a similar piece of code for a project, I noticed that SharePoint (or just IE) had trouble getting the MIME types correct. I ended up stripping it from the image to make it work, as below.
var raw = atob(base64.replace(/^data:image\/(png|jpg);base64,/, ""));
Uploading to SharePoint image library using the REST API and Ajax
If you decide to not go for an Angular module to upload your file, you can instead upload files directly to a SharePoint library through the REST API using normal ajax calls with jQUery. This might have to be modified for the Angular syntax, but the concept is the same.
var requestUrl = String.format("{0}/_api/web/lists/getByTitle('Images')/rootfolder/files/Add(url='{1}', overwrite=true)", _spPageContextInfo.siteAbsoluteUrl, fileName);
$.ajax({
url: requestUrl,
type: "POST",
data: buffer, //This is the base64 encoded buffer from the above step
processData: false,
headers: {
Accept: "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(result) {
console.log("Upload complete!");
},
error: function(error) {
console.log("Something went wrong!");
}
});

Resources