Sending data stored on a service - javascript

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) {
}; //
}

Related

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.

AngularJS - Best approach for taking data from factory and if not there use http service

In my angularJS application, I have set data received from one controller's ajax and put in factory method to reuse in other controllers. The problem is when user reload page, this factory method is useless.
app.factory('factory', function () {
return {
set: set,
get: get
}
});
app.controller ('testController', function ($scope, factory) {
if (factory.get('name')) {
$scope.name= factory.get('name');
} else {
$http.get(url).then(function(res) {
$scope.name= res.name;
factory.set('name', res.name);
});
}
});
What is the best way to retrieve this check in factory method which will get value from factory, if not there take from http service and in controller common code needs handle these two cases that done factory method?
Here when data taken from http service it returns promise otherwise plain value.
This code will fetch data from server if the 'cachedResult' variable is not set, otherwise return a promise from the stored variable.
app.factory('factoryName', ['$http','$q', function($http,$q) {
var cahedResult = null;
var myMethod = function(args) {
var deferred = $q.defer();
if (cahedResult){
deferred.resolve({ data : cahedResult });
return deferred.promise;
}
$http.get(....).then(function(response){
cahedResult = response.data;
deferred.resolve({ data : cahedResult });
},function(error){
deferred.reject('error');
});
}
};
return {
myMethod : myMethod
}
])
But you could also store the data in local storage or in a cookie when the first controller fetch the info so that it's available even if user refresh the browser.
First create a factory :
app.factory('factoryName', ['$http','$q', function($http,$q) {
return {
getData : function(arg1,arg2) {
return $http.get('/api-url'+arg1+'/'+arg2)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
}
}
}])
Provide every api details in this factory, so you can use this factory in multiple controllers.
In Controller inject the factory (factoryName) as a dependency.
app.controller ('testController',['$scope', 'factoryName', function($scope, factoryName) {
factoryName.getData(arg1,arg2,...)
.then(function(data) {
console.log(data);
}, function(error){
console.log(error);
});
}]);
For detailed description :- http://sauceio.com/index.php/2014/07/angularjs-data-models-http-vs-resource-vs-restangular/
Directly return a promise from your factory
app.factory('factoryName', function () {
var connectionurl ='...'; //Sample: http://localhost:59526/Services.svc
return {
connectionurl : connectionurl ,
methodName: function (parameters) {
$http({
method: 'GET',
url: connectionurl + 'servicemethod_name'
})}
}
}
});
In this case your controller will look like
app.controller ('testController', function ($scope, factoryName) {
factoryName.methodName(parameters).then(function(){
$scope.variable=response.data;
/*binding your result to scope object*/
}, function() {
/*what happens when error occurs**/
});
});
Other way is directly bind to a scope object through success callback function
app.factory('factoryName', function () {
var connectionurl ='...'; //Sample: http://localhost:59526/Services.svc
return {
connectionurl : connectionurl ,
methodName: function (parameters,successcallback) {
$http({
method: 'GET',
url: connectionurl + 'servicemethod_name'
}).success(function (data, status, headers, config) {
successcallback(data);
})
.error(function (data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}
}
});
In this case your controller will look like
app.controller ('testController', function ($scope, factoryName) {
factoryName.methodName(parameters,function(response){
/* your success actions*/
$scope.variable=response;
});
});
In the second case your error is handled in the factory itself. How ever you can also use errorcallback function.

How to handle Angular $http result in a Factory

I am using a Angular factory, service and a controller. I use the service to $http get data from a url, send it to the factory who then handles the response data and sends a object to the controller:
Service:
module.exports = function($http, $q){
return {
getOptions: function () {
var deferred = $q.defer();
$http({ method: "GET", url: AppAPI.url + 'acf/v2/options/' })
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
}
};
Factory:
module.exports = function(optionsService){
var options = {};
var getOptions = optionsService.getOptions();
getOptions.then(function(items){
options = items;
});
return options;
};
Controller:
module.exports = function($scope, $http, optionsFactory){
console.log(optionsFactory);
};
But the Factory returns an empty options to the controller. How would you assign the items from the promise to the options object which get's returned to the controller?
UPDATE
Here is a fiddle
Would appreciate the help :)
Could you try changing
var getOptions = optionsService.getOptions();
// to
var getOptions = optionsService.getOptions;
If you created a plunkr/fiddle, that would help a bit.

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