Get data from angular post method - javascript

I have an angular controller with an http.post request but I'm not getting response, the service works fine because a test it using postman.
I need to display the data from the WS in an HTLM table(I know how to do this part) when the page is loaded, I'm sendinng the body for the request in a variable name "data", the header configuration un a variable name "config" and the the http.post call to the URL of my WS.
I'm new to angular so I don't know if I'm missing something, also I want to print the response in the console to test if it's returnig what I'm expecting.
I took this code from an example I found on the web and I modify it, in the example there's a button where the call to SendData() function but I don't need a button, the call has to be made as the page is loaded.
This is the controller code
.controller("HttpGetTestController", function ($scope, $http) {
$scope.SendData = function () {
var data = {
"userId":"mdrodri",
"token":"840430482834947828876768058086529370654",
"domain":"MX",
"filters":{
"timeFrameType":"Week (FiscalYear)",
"custMembSelectionType":"TOTAL",
"locationSelectionType":"Country",
"merchandiseSelectionType":"SBU",
"startYear":"2015",
"endYear":"2015",
"startUnit":"1",
"endUnit":"1",
"comparator":false,
"locationSelections":["CA"],
"merchandiseSelections":["SBU38"],
"custMembSelections":["TOTAL"],
"metricSelections":["Product Sales (Category Rank)"],
"rankOrder":"10"
},
"additionalFilters":[],
"cache":false
};
var config = {
headers : {
'Content-Type': 'application/json;'
}
}
$http.post('http://whateverurl/', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
console.log("Success");
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
console.log("Data: " + data);
console.log("Status: " + status);
console.log("Headers: " + header);
console.log("Config: " + config);
});
};
})
In my HTML this is how I'm calling that controller
<div class="panel panel-default" ng-controller="HttpGetTestController">
Thank's for the time and help.

You need to call $scope.SendData() function in the controller :
.controller("HttpGetTestController", function ($scope, $http) {
$scope.SendData = function () {
//your code ...
}
//then the calling
$scope.SendData();//here
}

Related

Test an Angular service by expecting a function call: Jasmine createSpy

I have a controller that calls a service function, by passing in 2 functions as parameters (to be called dependent on the outcome of the service function), like so:
Controller code:
onSuccess(data){ ... }
onError(data){ ... }
service.post(url, query, onSuccess, onError);
Service code:
var service = function($log, $http, $location, $interval) {
...
var post = function(url, query, onSuccess, onError){
$http.post(url, query)
.success(function(data, status, headers, config){
onSuccess(data);
})
.error(function(data, status, headers, config){
onError(data);
});
};
...
});
What I'm trying to do is test that the query passed into the post function is correct and so the onSuccess function located within the controller code is called. I've tried to test this like so:
Test code:
describe("post", inject(function (service) {
beforeEach(module('myApp'));
beforeEach(function() {
var url = "http://..."
var query = {
...
}
var mockSuccess = jasmine.createSpy('Success function');
var mockError = jasmine.createSpy('Error function');
service.post(url, query, mockSuccess, mockError);
}
it('Should call success function following call to http.post', function () {
expect(mockSuccess).toHaveBeenCalled();
});
))};
Although I'm getting the error:
TypeError: null is not an object (evaluating 'currentSpec.$modules')
So I'm not sure how to properly test whether my query is successful in returning data through the http request?
Thanks in advance.

How to pass or fetch data from AngularJS to Aspx using WebMethod?

I have to fetch a string from aspx to angularJS and display it. But I am not getting any response or it might be AngularJS is not triggering the method.
Here is my Angular Controller
controller('ReadTextController', function ($scope, $http, $location) {
$scope.showData = function () {
$http.post('KeyPhraseGroup.aspx/GetEmployees', { data: {} })
.success(function (data, status, headers, config) {
$scope.result = data.d;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
});
And here is my aspxmethod
[WebMethod]
public static string GetEmployees()
{
return "Hello World";
}
I am triggering the showData() method of the AngularJS controller in my html page but not getting the string fetched.
Changed Explanation
I am getting value as undefined

AngularJS : Getting Error on adding $scope in factory-service

studentService.js
app.factory('saveStudentService',['$http','$scope',function ($http,$scope) {
var studentData = {};
studentData.save = function(jsondata){
var action = "student";
var method = "POST";
$http({
url: action,
method: method,
headers: {'Content-Type': 'application/json'},
data: jsondata
}).success(function(data, status, headers, config) {
toastr.success(status +' : Data has been submitted successfully ');
}).error(function(data, status, headers, config) {
toastr.error(status + ' : Data has not been submitted successfully ');
});
};
return studentData;
}]);
I am getting this error
angular.js:13642Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20saveStudentService
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:6:412
If from studentService.js, $scope is being removed, i.e
app.factory('saveStudentService',['$http',function ($http) {
this code is working properly, and not getting any error message in console.
Following is the studentController.js file from where this studentService is being called.
StudentController.js
app.controller('saveStudentCtrl',['$scope', 'saveStudentService', function($scope,saveStudentService) {
$scope.submit_create_student = function() {
var jsondata = $scope.student;
saveStudentService.save(jsondata);
}
}]);
but if same thing i.e $scope is being added in the updateStudentService then this code is working as expected.
app.controller('updateStudentCtrl',['$scope','retriveStudentService', 'updateStudentService', function($scope,retriveStudentService, updateStudentService) {
$scope.getStudentDataFromServer = function() {
retriveStudentService.get();
};
$scope.submit_update_student = function(e) {
updateStudentService.update();
}
}]);
Could someone please clarify, what is happening here. Though able to use same thing in one place, but not able to use same process at someother place.
You cannot inject scope into services. You can inject it to controllers.

Sending data stored on a service

I have the following controller and service
angular
.module('myApp')
.controller('Spliptter', Spliptter) // Controller
.service('SplitService', SplitService); //Service
function Spliptter($scope, SplitService){
var result = SplitService.phoeNoSplit($scope.phoneNumber.number); //Phone Data
$scope.area: result['area'];
$scope.country: result['country'];
}
function SplitService() {
this.phoeNoSplit = function(phoneNumber) {
var area = phoneNumber.substring(0, 3); //Info that I want to send
var country = phoneNumber.substring(3, 10); //Parse
return {
'area': area,
'country': country
}
}
}
Also I have a form where I use to send the area code and the country code.
angular //Controller of the form that i'm using to send the area and country code
.module('myApp')
.controller('formController', formController); // Form controller
function formController($scope, $http, $rootScope) {
$scope.SendFormController = function () {
$http({
method:'POST',
url:myURL.com,
data : {
ciaPhone: $scope.TokenResponse.datos.ciaPhone,
phoneCountry: $scope.country,
phoneArea: $scope.area
}
}, // form fields
headers: {
'Content-Type': 'application/json'
}//
})
.success(function ( data, status, headers) {
$rootScope.datosPersonales = data;
})
.error(function (data, status, header, config) {
}; //
}
But, I dont know whats the problem. I'm new in angular.
Please read angular docs first so that you will get better understanding how controller and service works.
Here issue is you are trying to access the scope of Spliptter controller into formController controller which will never possible.
If you have to use that scope values in formController then you will have to initialise those scope values in formController itself.
Refer below code:
formController
angular //Controller of the form that i'm using to send the area and country code
.module('myApp')
.controller('formController', formController); // Form controller
function formController($scope, $http, $rootScope, SplitService) {
var result = SplitService.phoeNoSplit($scope.phoneNumber.number);
$scope.area: result['area'];
$scope.country: result['country'];
$scope.SendFormController = function () {
$http({
method:'POST',
url:myURL.com,
data : {
ciaPhone: $scope.TokenResponse.datos.ciaPhone, // am not sure from where you are getting it
phoneCountry: $scope.country,
phoneArea: $scope.area
}
}, // form fields
headers: {
'Content-Type': 'application/json'
}//
})
.success(function ( data, status, headers) {
$rootScope.datosPersonales = data;
})
.error(function (data, status, header, config) {
}; //
}

ngResource query returns strange objects

I am new to AngularJS and wanted to try out the $resource functionality.
I have this code:
.factory('GetTasksService', function($resource, BASE_URL) {
return $resource(BASE_URL + 'api/tasks');
})
.controller('TasksCtrl', function ($scope, $http, BASE_URL, GetTasksService) {
$scope.tasks = GetTasksService.query();
$scope.getTasks = function () {
$http({ url: BASE_URL + 'api/tasks', method: 'GET' })
.success(function (data, status, headers, config) {
$scope.tasks = data;
})
.error(function (data, status, headers, config) {
alert("call did not work");
});
}
});
The getTasks function works as expected - returning an array of:["taska", "taskb"] as it should.
The GetTasksService.query() however returns an array of [{"0":"t","1":"a","2":"s","3":"k","4":"a"}, {"0":"t","1":"a","2":"s","3":"k","4":"b"}]
Can anyone tell me what I am doing wrong?
There is an option when specifying an action for an ngResource called isArray;
The default action query sets this as true by default, so you need to set set the action like:
query : {
method : 'GET',
isArray : false
}

Categories