http get and post Angular - javascript

Hello here's my json "names" :
[
{
"file": "file1.zip",
"date": "12-03-2016",
},
{
"file": "file2.zip",
"date": "24-06-2016",
},
{
"file": "file3.zip",
"date": "02-12-2016",
}]
My javascript file:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('newapi.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function(){
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service){
var promise = service.getNames();
promise.then(function(data){
$scope.names = data.data;
$scope.namesplit = $scope.names;
$scope.namesplit.map(function(item) {
item.time = new Date(item.date * 1000);
});
console.log($scope.namesplit);
});
});
and HTML :
<tr ng-repeat="name in names">
<td>{{name.file}}</td>
<td>{{name.date}}</td>
<td><button>POST</button></td>
</tr>
Well i have a table and what i need is when i click on button, the "file" post to serwer. I know i must use $http.post but i don't know how to do it.

So Simple
Html
<button ng-click="post()">Click Me</button>
Controller
$scope.post=function(){
$http.post(URL HERE, data-here, {
})
.then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
}

For upload a file using $http.post() function you have to set some additional parameters like headers and and transformRequest.
Here a simple example:
$scope.postToServer = function(){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
Note: in this example the file var is the content of the file located on client file system and the uploadUrl is the URL of your service that handle the request.

Related

$http post request breaks rest of angularjs code

I just started learning Angularjs and I am facing a peculiar problem. If I get my $http post to work, the rest of my code doesn't, and the other way around- if everything else works my $http post doesn't. Does it have to do with my controller? Should I use a factory?
angularjs file:
var app = angular.module('emailApp', []);
app.controller('EmailController', function($scope, $http) {
$http({
method: "post",
url: "php.php",
data: $.param($scope.composeEmail),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response){
$scope.data = response.data;
});
$scope.isPopupVisible = false;
$scope.isComposePopupVisible= false;
$scope.composeEmail = {};
$scope.activeTab = "inbox";
$scope.sentEmails = [];
$scope.sendEmail = function() {
$scope.isComposePopupVisible = false;
$scope.composeEmail.date = new Date();
$scope.sentEmails.push($scope.composeEmail);
};
$scope.showComposePopup = function() {
$scope.composeEmail = {};
$scope.isComposePopupVisible = true;
};
$scope.showPopup = function(email) {
$scope.isPopupVisible = true;
$scope.selectedEmail = email;
};
});

How to Pass Data in Angularjs

firstapp
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
sencond app
var app = angular.module('myApp2', []);
app.controller('myCtrl2', function($scope, $http) {
$http.get("fsd.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
How to Pass data from one app to another app in angularjs ?
You can use shared service to communicate between two angular apps.
However using multiple apps is not a good practice unless it is the only option left.
angular.module('sharedService', []).factory('SharedService', function() {
var SharedService;
SharedService = (function() {
function SharedService() {}
SharedService.prototype.setData = function(name, data) {};
return SharedService;
})();
if (typeof(window.angularSS) === 'undefined' || window.angularSS === null) {
window.angularSS = new SharedService();
}
return window.angularSS;});
angular.module("angularApp1", ['sharedService'])
/*code */
angular.module("angularApp2", ['sharedService'])
/*code */
Create function like this in Service Lyaer
editTool: function(yourData) {
var basicAuth = YOurauthenticateFuntion;
var url = 'url';
var deferred = $q.defer();
$http.post(url, yourData, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': basicAuth
}
}).then(function(data) {
if(data.status == 200) {
deferred.resolve(data.data);
} else {
deferred.reject(data);
}
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
and then can call in any controller using factory name.. that you have created for serviceCalls

Image upload using rest api in Angularjs

I have to upload image using rest api for successfull upload will get the response of file folder destination ex: D:/ddd/download,I am not able to upload image, below is my code given suggest me any corrections. while uploading image i have to give parameter name as fileData.
api ex: http://somelink and parameter for post is fileData
Html code
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
my service and directive
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
my controller file
$scope.uploadFile = function(){
var data={
'fileData':$scope.myFile
}
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(data, uploadUrl).success(function(response) {
$scope.fileName=response;
})
};
Please check on this...
Controller:
$scope.uploadFile = function () {
var file = $scope.myFile;
console.log(file);
if(file.type==='image/jpeg' || file.type==='image/jpg' || file.type==='image/png' ){
var uploadUrl = "http://";
fileUpload.uploadFileToUrl(file, uploadUrl);
angular.element('input[type="file"]').val(null);
}else{
$scope.errorMessage='File Type Error';
}
};
Service:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, url) {
var uploadUrl = url;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
console.log("Image Save");
})
.error(function () {
});
};
}]);
You want to pass a the file itself to the formdata object
fileUpload.uploadFileToUrl($scope.myFile, uploadUrl).success(function(response) {
$scope.fileName=response;
})
and set the first parameter of append as fileData
fd.append('fileData', file);
Hi friends now the image upload is working, i have removed service and done changes to my controller by adding below code.
var file = $scope.myFile;
var uploadUrl = "http://";
var fd = new FormData();
fd.append('fileData', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(response){
$rootScope.fileValue = response;
})

Can not read property then of undefined error in angular JS

This is my angularJS service and controller.
sampleApp.factory('BrandService', function($http, $q) {
var BrandService = {};
var BrandList = [];
BrandService.GetBrands = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: BrandURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( BrandList.length == 0 )
{
$http(req)
.success(function(response) {
BrandList = response.data
alert ('Brand Fetching is successful');
return response.data;
})
.error(function (data, status, headers, config) {
alert ('Brand Fetching Error');
alert (status);
alert (data);
});
}
else
{
var deferred = $q.defer();
deferred.resolve(BrandList);
return deferred.promise;
}
}
return BrandService;
});
sampleApp.controller('BrandController', ['$scope', 'BrandService', function ($scope, BrandService){
$scope.Brands = [];
$scope.GetBrands = function() {
BrandService.GetBrands().then(function(data) {
$scope.Brands = data;
});
};
$scope.GetBrands();
}]);
When controller is loading I m seeing the following error.
Cannot read property 'then' of undefined
at l.$scope.GetBrands (Controllers.js:337)
Can please someone help me what i m doing wrong?
You are not returning promise in case of HTTP request when data is not yet cached.
Correct code would be:
sampleApp.factory('BrandService', function($http, $q) {
var BrandService = {};
var BrandList = [];
BrandService.GetBrands = function() {
var req = {
url: BrandURL,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({Action: 'GET'})
};
if (BrandList.length) {
return $q.when(BrandList);
}
return $http(req)
.success(function(response) {
BrandList = response.data
alert('Brand Fetching is successful');
return response.data;
})
.error(function(data, status, headers, config) {
alert('Brand Fetching Error');
alert(status);
alert(data);
});
}
return BrandService;
});
Also you don't need to create dummy deferred object, you can return resolved promise with $q.when.

How to call ajax from service in AngularJS?

I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User.
When i debug the code i found that it call success first and then it goes for Ajax call.
When i do ajax call without service it works fine.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
this.SearchEmployee = function () {
// Ajax call
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.userUsers = response.data;
this.errors = '';
};
var onError = function (reason) {
this.userUsers = reason;
this.errors = "Error in retrieving data.";
};
return this.Users;
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.Id = '';
this.name = '';
this.expertise = '';
$scope.repoSortOrder = 'id';
$scope.filterField = '';
// Call to service
this.GetAllEmployee = function () {
// Initiates the AJAX call
$scope.User = EmployeeSer.SearchEmployee();
// Returns the promise - Contains result once request completes
return true;
};
this.AddEmployee = function () {
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
$http({
method: 'POST',
url: '/Home/Create',
params: JSON.stringify(empData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
// Returns the promise - Contains result once request completes
return true;
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
It's because you are returning the users before the data is fetched from the server. Also it doesn't seem like you are assigning them correctly.
Here are two ways to solve the problem:
Firstly. You bind your controller user-data to the user-data in the service.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.Users = response.data;
this.errors = '';
};
var onError = function (reason) {
this.users = null;
this.errors = "Error in retrieving data.";
};
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.users = EmployeeSer.users;
EmployeeSer.SearchEmployee();
}]);
And the second way would be to return the promise in the service and unwrap it in the controller.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.SearchEmployee = function () {
return $http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.GetAllEmployee = function () {
EmployeeSer.SearchEmployee()
.then(onSuccess, onError)
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
OFF TOPIC
You should probably consider using ngModel instead of jQuery to get you data to the controller.
Not like this:
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
// Here serverRequest is my service to make requests to the server
serverRequest.postReq = function(url, data, sucessCallback, errorCallback){
$http({
method: 'POST',
url: urlToBeUsed,
data:data,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, headers, config) {
sucessCallback(data);
})
.error(function(data, status, headers, config){
errorCallback(data);
})
}
// In the controller
serverRequest.postReq('urlToBeCalled', dataToBeSent, scope.successCb, scope.errorCb);
scope.successCb = function(data){
// functionality to be done
}
scope.errorCb = function(data){
// functionality to be done
}
Try it this way your problem might be solved
Promise must be unwrapped in your controller if you want to use it

Categories

Resources