Error 404 while sending a file using $http AngularJs - angularjs

I'm trying to get a file using $http, I tested my code in another application and it's working well but in my application I get this error:
this is my code:
app.controller("directoryCtrl", ["$scope", "$http", "Restangular", "langFctr", "$translate", function($scope, $http, Restangular, langFctr, $translate) {
$scope.uploadFile = function(files) {
var fd = new FormData();
fd.append("file", files[0]);
$http.post("/input", fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).then(function successCallback(response) {
console.log("ok");
}, function errorCallback(response) {
console.log(response);
});
};
}]);

Related

Error: unable to get property 'call' of undefined or null reference

I am using AngularJs. When getting data from controller.js to service.js, I am getting the error. Below is the code used:
//controller.js
angular.module('testApp.controllers', []).
controller('testController', function ($scope, testAPIService, $timeout, $window, $location, $anchorScroll, $http) {
$scope.show = function() {
testAPIService.getDataSummary().success(function (response) {
console.log(response);
}).error(function (response) {
alert(response.responseText);
});
}
});
In Service.js
angular.module('testApp.services', []).
factory('testAPIService', ['$http', function ($http) {
var testAPIService = {};
testAPIService.getDataSummary = function () {
var request = {
url: urlBase + 'GetDataSummary',
method: 'Get',
headers: {
'accept': 'application/json'
}
}
return $http(request);
};
return testAPIService;
}]);
How to fix this? Thanks
This might be the result of including any of your app javascript file before the angularjs file.
Make sure you include angularjs file before the rest of your app files.
You're creating two different modules:
The first module testApp.controllers is created when you create the controller
Another module testApp.services is created when you create the service.
So the controller and the service are never part of the same module!
Try attaching to the same testApp module as follows:
app.js
// With [] means to create a new module.
angular.module('testApp', []);
controller.js
// Without [] means to retrieve an existing module.
angular.module('testApp').
controller('testController', function($scope, testAPIService, $timeout, $window, $location, $anchorScroll, $http) {
$scope.show = function() {
testAPIService.getDataSummary().success(function(response) {
console.log(response);
}).error(function(response) {
alert(response.responseText);
});
}
});
service.js
// Without [] means to retrieve an existing module.
angular.module('testApp').
factory('testAPIService', ['$http', function($http) {
var testAPIService = {};
testAPIService.getDataSummary = function() {
var request = {
url: urlBase + 'GetDataSummary',
method: 'Get',
headers: {
'accept': 'application/json'
}
}
return $http(request);
};
return testAPIService;
}]);
index.html
And change your ng-app directive to point to the testApp module
<html ng-app="testApp">

How to make $resource.post call without sending data

I have done this using $http.post as below:
$http({
method: 'POST',
url: 'www.someurl'+myid
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
Requirement is to make the same post call using $resource. I tried as below:
filter:
saffModuleServices.factory('Projects', ['$http', '$resource', '$appConstants',
function ($http, $resource, $appConstants) {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
var createDraftEndPoint=www.someurl/:id;
var saveEmailDraftEndPoint=www.someurl.com
return {
saveEmailDraft: function(){
return $resource(saveEmailDraftEndPoint, {}, {
update: {method: 'PUT', params: {},headers: {'Content-Type':'application/json'}}
});
},
createDraft: function(){
return $resource(createDraftEndPoint, {}, {
post: {method: 'POST',param{id:''}}
});
},
}
}]);
controller:
saffModuleControllers.controller('ctrl', ['$scope', 'SaffNotification','Projects','$filter',
function ($scope, Notification,Projects,$filter) {
Projects.createDraft().post({id:myid}, function(response){
Notification.success({message: $filter('translate')('administration_item_save_notification'), templateUrl: 'common/templates/toastr_success_template.html'});
}, function(response){
Notification.error({message: response.data.errorMessage, templateUrl: 'common/templates/toastr_error_template.html'});
});
}]);
error:
myId is going as data for this request, but I want to send that as param and no data should be sent. I could do that using $http.post
Can anyone suggest me how to make this request in $resource.post without editing $httpProvider in config, because I dont want to make 'data' parameter nil for other POST request.

How can Angular Service Function return response to controller

Actually, I am uploading image using service, image uploaded successfully, but I want responded data to the function in controller.
Controller:
adminApp.controller('imageController', ['$scope', 'fileUpload', 'Images',function ($scope, fileUpload, Images) {
$scope.uploadFile = function (data) {
console.log(data);
var file = data.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "/image";
fileUpload.uploadFileToUrl(file, data, uploadUrl);
// $scope.images.push();
};
}]);
Service:
adminApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, data, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
})
.error(function () {
});
}
}]);
laravel (backhand):
public function store(Request $request)
{
$image = $request->file('file');
$image = $this->imageRepository->makeImage($image);
return $image;
}
I function in service return responded data from backhand to controller, so I can push the value to $scope.images in controllers function.
You can take advantage of angular $q here.
Updated Service Function
this.uploadFileToUrl = function (file, data, uploadUrl) {
var defer = $q.defer();
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
defer.resolve(data);
})
.error(function (error) {
defer.reject(error);
});
}
return defer.promise;
}]);
In your controller, you can use the function as
fileUpload.uploadFileToUrl(file, data, uploadUrl).then(function(response){
//response contains your data form service
}).catch(function(error){
// error variable contains error data from service.
});
the code is not tested.. but it should work or very close.

Angular - pass scope to service and set value

I cannot pass/set the value to the text-area outside the controller.
I am uploading an excel and regarding the upload status I want to set some data to a text-area.
This is my code so far:
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl, commentArea){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
/* commentArea.append('This is not working');
commentArea = 'This is not working';
$scope.outputImportObject = 'This is not working';
*/
alert('The file was succesfully uploaded!');
})
.error(function(){
alert('There was an error while inserting the file!');
});
}
}]);
app.controller('UploadCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
$scope.outputImportObject = 'This is working';
var file = $scope.myFile;
var commentArea = $scope.outputImportObject;
fileUpload.uploadFileToUrl(file, ws_url+'upload_excel.php',commentArea);
};
}]);
This typically seems a case where you should be using promises.
From your services you should return a promise and based on their resolution or rejection, you should bind the variable on controller.
your service should look something like:
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl, commentArea){
var fd = new FormData();
fd.append('file', file);
return
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}]);
Since, http itself return a promise, you can directly return it, instead of making your custom promise.
and your controller should be like:
app.controller('UploadCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
$scope.outputImportObject = 'This is working';
var file = $scope.myFile;
var commentArea = $scope.outputImportObject;
fileUpload.uploadFileToUrl(file, ws_url+'upload_excel.php',commentArea)
.then(doThisOnSuccess, doThisOnFailure);
function doThisOnSuccess(){
code for binding to text area should go here
}
function doThisOnFailure(){
}
};
}]);

Cannot set property from angularjs service

I am trying to set value in html page from angularjs controller.
I am getting value from web api in service but I have issue that I am always getting error:
TypeError: Cannot set property 'messageFromServer' of undefined
But I can't figure what am I doing wrong here. What am I missing?
On the html part I have:
<div ng-app="myApp" ng-controller="AngularController">
<p>{{messageFromServer}}</p>
</div>
In the controller I have:
var app = angular.module('myApp', []);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
$scope.messageFromServer = "When I set it here it works!"
messageService.getMessage();
}]);
app.service('messageService', ['$http', function ($http) {
this.getMessage = function ($scope) {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
$scope.messageFromServer = data;
console.log(data);
}).error(function (data) {
console.log(data);
})
};
}]);
Basically the problem is, you missed to $scope object to the service getMessage method. But this is not a good approach to go with. As service is singleton object, it shouldn't manipulate scope directly by passing $scope to it. Rather than make it as generic as possible and do return data from there.
Instead return promise/data from a service and then assign data to the scope from the controller .then function.
app.service('messageService', ['$http', function ($http) {
this.getMessage = function () {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
//you could have do some data validation here
//on the basis of that data could be returned to the consumer method
//consumer method will have access only to the data of the request
//other information about request is hidden to consumer method like headers, status, etc.
console.log(response.data);
return response.data;
}, function (error) {
return error;
})
};
}]);
Controller
app.controller('AngularController', ['$scope', 'messageService',
function ($scope, messageService) {
$scope.messageFromServer = "When I set it here it works!"
messageService.getMessage().then(function(data){
$scope.messageFromServer = data;
});
}
]);
Don't use $scope in your service, just return the promise from $http.
var app = angular.module('myApp', []);
app.service('messageService', ['$http', function ($http) {
this.getMessage = function () {
return $http({
method: "GET",
url: "api/GetMessage",
headers: { 'Content-Type': 'application/json' }
});
};
}]);
app.controller('AngularController', ['$scope', 'messageService', function ($scope, messageService) {
messageService.getMessage().then(function(data) {
$scope.messageFromServer = data;
});
}]);
In this example you can unwrap the promise in your controller, or even better you can use the router to resolve the promise and have it injected into your controller.
app.config(function($routeProvider) {
$routeProvider.when('/',{
controller: 'AngularController',
templateUrl: 'views/view.html',
resolve: {
message: function(messageService) {
return messageService.getMessage();
}
}
});
});
Then in your AngularController, you'll have an unwrapped promise:
app.controller('AngularController', ['$scope', 'message', function ($scope, message) {
$scope.messageFromServer = message;
}]);

Resources